Haskell - 如何将数字拆分为列表以进行进一步处理?

时间:2010-01-14 04:23:07

标签: haskell numbers split

我有一个Int,我想分成它的个别数字,理想情况下会包含在列表中,然后我可以进一步处理。所以我想要这样的事情:

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

有人熟悉这样的功能吗?

5 个答案:

答案 0 :(得分:22)

import Data.Char

map digitToInt $ show 245

答案 1 :(得分:4)

这里的例子适合你吗? 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))

示例:

> 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

答案 2 :(得分:2)

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

答案 3 :(得分:1)

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]

答案 4 :(得分:1)

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