How do i convert String into list of integers in Haskell

16,866

Solution 1

You can use

Prelude> map read $ words "1 2 3 4 5" :: [Int]
[1,2,3,4,5]

Here we use words to split "1 2 3 4 5" on whitespace so that we get ["1", "2", "3", "4", "5"]. The read function can now convert the individual strings into integers. It has type Read a => String -> a so it can actually convert to anything in the Read type class, and that includes Int. It is because of the type variable in the return type that we need to specify the type above.

For the string without spaces, we need to convert each Char into a single-element list. This can be done by applying (:"") to it — a String is just a list of Chars. We then apply read again like before:

Prelude> map (read . (:"")) "12345" :: [Int]
[1,2,3,4,5]

Solution 2

q1 :: Integral a => String -> [a]
q1 = map read . words

q2 :: Integral a => String -> [a]
q2 = map (read . return)

Error handling is left as an exercise. (Hint: you will need a different return type.)

Solution 3

There is a function defined in the module Data.Char called digitToInt. It takes a character and returns a number, as long as the character could be interpreted as an hexadecimal digit.

If you want to use this function in your first example, where the numbers where separated by a space, you'll need to avoid the spaces. You can do that with a simple filter

> map digitToInt $ filter (/=' ') "1 2 1 2 1 2 1"
[1,2,1,2,1,2,1]

The second example, where the digits where not separated at all, is even easier because you don't need a filter

> map digitToInt "1212121"
[1,2,1,2,1,2,1]

I'd guess digitToInt is better than read because it doesn't depend on the type of the expression, which could be tricky (which is in turn how i found this post =P ). Anyway, I'm new to haskell so i might as well be wrong =).

Solution 4

You can use:

> [read [x] :: Int | x <- string]
Share:
16,866
Rog Matthews
Author by

Rog Matthews

Updated on June 22, 2022

Comments

  • Rog Matthews
    Rog Matthews almost 2 years

    I have a String like "1 2 3 4 5". How can I convert it into a list of integers like [1,2,3,4,5] in Haskell? What if the list is "12345"?

  • aelguindy
    aelguindy over 12 years
    I think you mean q2 = .. not q2 ::