views:

388

answers:

4

Hi, i am currently trying to convert an integer into a list.

E.g.

1234 => List composed of 1, 2, 3, 4

I have this:

(string->list (number->string 1234))

Unfortunately it adds #'s and \'s to it. I am guessing this is a string representation of a number. How can i remove these symbols. Since i need to reorder the integers, and print out a list.

This is the output of the command above:

(#\1 #\2 #\3 #\4)

+4  A: 

Here's a function I wrote that breaks the number down by dividing by 10 each time:

(define (num->list num)
  (if (< num 10)
      (list num)
      (append (num->list (floor (/ num 10)))
              (list (- num (* 10 (floor (/ num 10))))))))

Obviously this will only work with positive integers, but if you need negatives it can be easily modified.

Kyle Cronin
A: 

I'm not familiar with scheme, but a slightly more code intensive, language-independent approach would be to use a math loop to get each digit out.

if 1234 is x: digit_1 = x%10 digit_2 = x%100 - digit_1 digit_3 = x%1000 - digit_2 - digit_1 etc.

You would need to add a check at each station, such that if x < 1000, stop after digit 3. Depending on the language, you can add a loop to this in various ways.

bigwoody
A: 

When you covert the string to a list, you are building a list of chars, thats why you get the #. #\ is the character delimiter.; so when you are done your list manipulation, you can reconvert it back to a string fairly easily.

Jonathan Arkell
+1  A: 

As Jonathan said, #\ means that it is a character. So you have to convert the character to number. Here is a simple way to do it.

(map (lambda (c) (- (char->integer c) 48))
         (string->list (number->string 1234)))
Peter B. Bock