Search code examples
recursionracketdigit

Digits of a number in Racket are in random order


I decided to write a function that given a number will return a list containing the digits in that number, my attempt is:

(define (rev-digits n)
  (if (= n 0)
    '()
    (cons (modulo n 10) (digits (quotient n 10)))))

(define (digits n)
  (reverse (rev-digits n)))

The fact is, I need the digits to be in proper order, but the function returns, for example:

> (digits 1234567890)
'(9 7 5 3 1 2 4 6 8 0)

In seemingly random order... can you help me getting a more ordinated output?


Solution

  • rev-digits needs to call itself, not digits.

    (define (rev-digits n)
      (if (= n 0)
        '()
        (cons (modulo n 10) (rev-digits (quotient n 10)))))
    
    (define (digits n)
      (reverse (rev-digits n)))
    

    should work.

    It's worth noting that your "random" output was not in fact random; rather the digits were "bouncing" back and forth from the start to the end of the list. Which makes sense, because you were effectively switching back and forth between a "normal" and reversed version of your digits function.