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.
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.
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") .
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With