Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing an integer

Tags:

scheme

racket

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.

like image 406
r-s Avatar asked Dec 09 '22 10:12

r-s


1 Answers

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
like image 196
Joshua Taylor Avatar answered Jan 16 '23 22:01

Joshua Taylor