Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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.

like image 892
peteofce Avatar asked Nov 13 '11 23:11

peteofce


People also ask

How do you convert a string from a space to a separated list?

To convert a string in a list of words, you just need to split it on whitespace. You can use split() from the string class. The default delimiter for this method is whitespace, i.e., when called on a string, it'll split that string at whitespace characters.

How do you convert a string to an integer in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .


1 Answers

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"
like image 147
Joey Adams Avatar answered Sep 30 '22 16:09

Joey Adams