简体   繁体   中英

How do i convert String into list of integers in Haskell

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" ?

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]
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.)

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 =).

您可以使用:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM