How to convert String to a list of integers in Haskell

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

+7
source share
4 answers

you can use

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

Here we use words to separate "1 2 3 4 5" into spaces to get ["1", "2", "3", "4", "5"] . The read function can now convert single lines to integers. It is of type Read a => String -> a , so it can actually convert anything to a class of type read and includes Int . This is because of the type variable in the return type, which we need to specify above.

For a string with no spaces, we need to convert each Char to a singleton list. You can do this by applying (:"") - a String is just a list of Char s. Then we apply read again, as before:

 Prelude> map (read . (:"")) "12345" :: [Int] [1,2,3,4,5] 
+21
source
 q1 :: Integral a => String -> [a] q1 = map read . words q2 :: Integral a => String -> [a] q2 = map (read . return) 

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

+8
source

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

If you want to use this function in the first example, where numbers are separated by a space, you need to avoid spaces. You can do this 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 numbers that are not separated at all is even simpler because you don't need a filter

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

I would suggest that digitToInt is better than reading, because it does not depend on the type of expression, which can be complex (which in turn is how I found this post = P). Anyway, I'm new to haskell, so I could be wrong =).

+2
source

You can use:

 > [read [x] :: Int | x <- string] 
0
source

All Articles