Alex Rivera | Logout

Convert string of whitespace separated numbers in a string into integers and place them in variables

Asked 2011-11-13T23:38:35.283
10

I'm trying to write a function(s) to accept a string of 4 whitespace separated numbers in a string, separate and convert them to integers, and place them in 4 individual integer variables. I know I can use splitWs to split them into a string array, use !! to access the individual elements, and something like the following to convert to integer:

f :: [String] -> [Int]
f = map read

But I can't figure out how to put it all together.

Edit
Report

1 Answer

16

Use the words function to split the string by whitespace. Then you can map read over the result.

Thus, a simple implementation would be:

readNumbers :: String -> [Int]
readNumbers = map read . words

Then, if you need exactly four numbers, use pattern matching:

case readNumbers string of
    [a,b,c,d] -> ...
    _         -> error "Expected four numbers"
answered 2011-11-14T00:29:36.083

Your Answer