int -> [int] convert
14,167
Solution 1
Solution:
digs 0 = [] digs x = digs (x `div` 10) ++ [x `mod` 10]
Source: link
Solution 2
This sounds like homework. Here's a general algorithm that you should be able to apply in Haskell:
- Convert the integer to a string.
- Iterate over the string character-by-character.
- Convert each character back to an integer, while appending it to the end of a list.
Good luck.
Solution 3
Using integer arithmetic:
digits' 0 = []
digits' n = n `rem` 10 : digits (n `quot` 10)
digits n = reverse (digits' n)
Solution 4
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
Solution 5
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
Related videos on Youtube
Comments
-
marco almost 2 years
Possible Duplicate:
Split a number into its digits with Haskellhow can i convert integer to integer list Exmple: input: 1234 output:[1,2,3,4] any idee about this problem ?
-
marco over 13 yearsI thank you very much that was the code i needed. and thanks for the other replies. cheers
-
Chris Dodd over 13 yearsOnly 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 -
sepp2k over 13 years@Chris: It does work for negative numbers.
digits (-42)
returns[-4, -2]
which seems sensible to me.