tags:

views:

199

answers:

6

Possible Duplicate:
Split a number into its digits with Haskell

how can i convert integer to integer list Exmple: input: 1234 output:[1,2,3,4] any idee about this problem ?

+7  A: 

This sounds like homework. Here's a general algorithm that you should be able to apply in Haskell:

  1. Convert the integer to a string.
  2. Iterate over the string character-by-character.
  3. Convert each character back to an integer, while appending it to the end of a list.

Good luck.

Mike Cialowicz
+1 for resisting the rep appeal and mentioning the *homework* word ;)
ring0
+4  A: 

Using integer arithmetic:

digits' 0 = []
digits' n = n `rem` 10 : digits (n `quot` 10)
digits n = reverse (digits' n)
sepp2k
Only problem is that `digits 0` gives you any empty list, but that's trivial to fix. Also doesn't work for negative numbers, but its not clear what the right answer is in that case
Chris Dodd
@Chris: It does work for negative numbers. `digits (-42)` returns `[-4, -2]` which seems sensible to me.
sepp2k
+1  A: 

Solution:

digs 0 = []
digs x = digs (x `div` 10) ++ [x `mod` 10]

Source: link

Margus
I thank you very much that was the code i needed. and thanks for the other replies. cheers
marco
+1  A: 

Alternatative solution using unfoldr:

import List
digits = reverse . unfoldr nextDigit
        where nextDigit 0 = Nothing
              nextDigit x = Just (r, q) where (q, r) = quotRem x 10
jleedev
A: 

jleedev:

I did something similar with divMod. I did not know that quotRem existed!

import Data.List ( unfoldr )

listify :: Integer -> [Integer]
listify = reverse . unfoldr f
   where
      f i = case divMod i 10 of
         (0, 0) -> Nothing
         (w, r) -> Just (r, w)
dino
+2  A: 

What about this quite simple solution?

import Data.Char (digitToInt)

int2intList :: Integral i => i -> [Int]
int2intList s = map digitToInt $ show s

main = print $ int2intList 12351234999123123123

gives [1,2,3,5,1,2,3,4,9,9,9,1,2,3,1,2,3,1,2,3]

This one is possible and a bit more universal, too:

int2intList :: (Read i, Integral i) => i -> [i]
int2intList s = map (read.(:[])) $ show s

main = print $ int2intList 12351234999123123123
Johannes Weiß