Read the line with getLine, divide it into wordsand readeach:
readInts :: IO [Int]
readInts = fmap (map read.words) getLine
it reads any number of messages:
ghci> readInts
1 2 3
[1,2,3]
ghci> readInts
1 2 3 4 5 6
[1,2,3,4,5,6]
You can limit three:
read3Ints :: IO [Int]
read3Ints = do
ints <- readInts
if length ints == 3 then return ints else do
putStrLn ("sorry, could you give me exactly three integers, "
++ "separated by spaces?")
read3Ints
which is as follows:
ghci> read3Ints
1 2
sorry, could you give me exactly three integers, separated by spaces?
1 23 , 5, 6
sorry, could you give me exactly three integers, separated by spaces?
1,2,3
sorry, could you give me exactly three integers, separated by spaces?
1 3 6
Secrets fmap
fmapworks a bit like map, but you can use it more widely:
ghci> fmap (*10) [1,2,3,4]
[10,20,30,40]
ghci> fmap (*10) (Just 5)
Just 50
ghci> map (fmap (*10)) [Left 'b', Right 4, Left 'c', Right 7]
[Left 'b',Right 40,Left 'c',Right 70]
ghci> fmap words getLine
Hello there me hearties!
["Hello","there","me","hearties!"]
getInts fmap (map read.words), , map read, Int. , Int - - , .