Search code examples
scheme

Reverse the digits of a number using a list


I would like to reverse the numbers of a digit by using a list in Scheme. So far my logic is to get the modulo of the number by 10 and append that number to a list. In each recursive call the number is decreased by dividing it by 10. So far my code is the following:

(define (reverse n L)
 (let ((r (remainder n 10)))
    (if (= n 0)
        L
        (begin
          ((append L (list r))
           (reverse (/ n 10) L))))))

The problem that I got is when I input a value, for example 123, is the following:

remainder: contract violation
  expected: integer?
  given: 123/10
  argument position: 1st
  other arguments...:

What am I missing?


Solution

  • In Scheme when you divide two integers, in the result you get integer or ratio. 123/10 is a ratio (because you can't divide 123 by 10 and get integer).

    If you want to convert it to integer, you have to floor or ceil it.