开发者

int -> [int] convert [duplicate]

This question already has answers here: 开发者_运维百科 Closed 12 years ago.

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 ?


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.


Solution:

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

Source: link


Using integer arithmetic:

digits' 0 = []
digits' n = n `rem` 10 : digits (n `quot` 10)
digits n = reverse (digits' n)


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


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:

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)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜