I am trying to write a function which takes an input number and outputs the number in reverse order.
Ie:
Input -> 25 Output -> 52
Input -> 125 Output -> 521
I am new to lisp, if its helpful here is the working function in c++
function.cpp
int revs(int rev, int n)
{
if (n <= 0)
return rev;
return revs((rev * 10) + (n % 10), n/10);
}
I have written it in Racket as follows:
(define (revs rev n)
(if (<= n 0)
rev
(revs (+ (* rev 10) (modulo n 10)) (/ n 10))))
But when I run it with (revs 0 125) I get this error:
modulo: contract violation
expected: integer?
given: 25/2
argument position: 1st
other arguments...:
10
Certainly I am doing something incorrect here, but I am unsure of what I am missing.
The division operator /
doesn't do integer division, but general division, so when you call, e.g., (/ 25 2)
, you don't get 12
or 13
, but rather the rational 25/2
. I think you'd want quotient
instead, about which the documentation has:
procedure (quotient n m) → integer? n : integer? m : integer?
Returns
(truncate (/ n m))
. Examples:> (quotient 10 3) 3 > (quotient -10.0 3) -3.0 > (quotient +inf.0 3) quotient: contract violation expected: integer? given: +inf.0 argument position: 1st other arguments...: 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With