views:

444

answers:

5

I have an Int that i want to split into it's individual numbers which ideally would be contained in a list, which i can then process further. So i would like something like this:

split 245
--will then get an list containing [2,4,5]

Is anyone familiar with such a function?

+13  A: 
import Data.Char

map digitToInt $ show 245
Michał Marczyk
nice example..!
jspcal
so i strap digitToInt onto a show command of a number?
RCIX
Yes, if you want to use this approach... Just take care to pass in nonnegative numbers only. Otherwise you'd be passing a `'-'` to `digitToInt`, which is an error. Incidentally, John Boker's cool answer has a funkier issue with negative numbers... check it out. :-)
Michał Marczyk
Yes, the basic idea of this is that you use "show" to convert 245 to a string, which is a list of characters. Then you map digitToInt over this list of characters, and you get digits in place of characters, so you have a list of digits.
avpx
+4  A: 

would the example here work for you ? http://snippets.dzone.com/posts/show/5961

convRadix :: (Integral b) => b -> b -> [b]
convRadix n = unfoldr (\b -> if b == 0 then Nothing else Just (b `mod` n, b `div` n))

example:

> convRadix 10 1234
[4, 3, 2, 1]
> convRadix 10 0
[]
> convRadix 10 (-1)
[9,9,...] (infinite)

to convert haskell radix by mokehehe on Thu Aug 21 08:11:39 -0400 2008
John Boker
I'd write it more like `convRadix b = unfoldr mModDiv where mModDiv 0 = mzero; mModDiv n = let (q, r) = n \`divMod\` b in return (r, q)` (split across lines, which I can't do in a comment) but it's really all the same :)
ephemient
A: 
digits :: (Integral a) => a -> [a]
digits = flip digits' [] . abs

digits' :: (Integral a) => a -> ([a] -> [a])
digits' n = if q == 0
  then (r :)
  else (digits q ++) . (r :)
  where
    (q, r) = n `divMod` 10

digits   1234  == [1, 2, 3, 4]
digits (-1234) == [1, 2, 3, 4]
trinithis
Or `digits = fst . head . filter ((==) 0 . snd) . tail . iterate (\(d, n) -> let (q, r) = n \`divMod\` 10 in (r:d, q)) . (,) [] . abs` ;-)
ephemient