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"
?
-
10-1, Can you add the code you have tried with?Reddy– Reddy2012年01月16日 11:34:33 +00:00Commented Jan 16, 2012 at 11:34
4 Answers 4
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 Char
s. We then apply read
again like before:
Prelude> map (read . (:"")) "12345" :: [Int]
[1,2,3,4,5]
Comments
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.)
2 Comments
return
will pick up a single Char, say '1', and return it in the context of a String (to be fed to read
which expects one)? So, it is returned in a general "context", which we specify at the end as context of a list (of Ints)? Kinda makes sense. I have to start thinking more in this kind of way. So, thanks!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 =).
Comments
You can use:
> [read [x] :: Int | x <- string]
1 Comment
map (\x -> read [x] :: Int) string