0

I am trying to write a function which takes a number and returns a list of the number's digits. For example:

(list-num 648)
;=> (6 4 8)

I have written some code, but it returns (8 4 6), and I can't use reverse. MY code so far:

(define (list-num n)
  (if (not (equal? (quotient n 10) 0))
      (cons (modulo n 10) (list-num(quotient n 10)))
      (cons (modulo n 10) '())))
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
  • 1
    This is probably a duplicate. Some related questions include: [Converting a list of digits to a number](http://stackoverflow.com/q/19554279/1281433), which goes in the other direction; and [Improving performance for converting numbers to lists, and base10 to base2](http://stackoverflow.com/q/19822227/1281433), which involves transforming numbers to lists of digits. – Joshua Taylor Feb 25 '14 at 16:32
  • 1
    Here we go: this is duplicate of [Convert number to list of digits](http://stackoverflow.com/q/8014453/1281433). – Joshua Taylor Feb 25 '14 at 16:40

2 Answers2

1

You can use your function as the inner function and wrap an outer function that does the reverse:

(define (list-num n)
  ; inner function - your initial function      
  (define (sub n)
    (if (not (equal? (quotient n 10) 0))
        (cons (modulo n 10) (sub (quotient n 10)))
        (cons (modulo n 10) '())))
  ; call inner function
  (reverse (sub n)))

then

> (list-num 648)
'(6 4 8)

You could also use a named let and an accumulator:

(define (list-num n)
  (let loop ((n n) (acc '())) ; named let, acc=accumulator
    (let ((q (quotient n 10)) (r (remainder n 10)))
      (if (= q 0)
          (cons r acc)
          (loop q (cons r acc))))))
uselpa
  • 18,732
  • 2
  • 34
  • 52
1

In Common Lisp:

CL-USER 21 > (map 'list #'digit-char-p (princ-to-string 648))
(6 4 8)
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346