开发者

Haskell -- How to split a number into a list for further processing?

I have an Int that i want to split into it's individual numb开发者_开发知识库ers 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?


import Data.Char

map digitToInt $ show 245


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


digits :: Int -> [Int]
digits 0 = []
digits n = digits k ++ [r]
    where k = div n 10; r = mod n 10


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]


digits = reverse . map (`mod` 10) . takeWhile (> 0) . iterate (`div` 10) . abs
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜