例如,我想编写一个程序,它将从命令行输入3个整数作为输入.我学到的功能是readLn从整行读取值.但readLn似乎将整行解析为单个值.如何使用haskell获取一行的三个值?
And*_*ewC 14
阅读带线getLine,它拆分成words,并且read每个:
readInts :: IO [Int]
readInts = fmap (map read.words) getLine
Run Code Online (Sandbox Code Playgroud)
它读取任意数量的Ints:
ghci> readInts
1 2 3
[1,2,3]
ghci> readInts
1 2 3 4 5 6
[1,2,3,4,5,6]
Run Code Online (Sandbox Code Playgroud)
你可以限制为三个:
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
Run Code Online (Sandbox Code Playgroud)
看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
fmapfmap有点像map,但你可以更广泛地使用它:
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!"]
Run Code Online (Sandbox Code Playgroud)
在getInts,我做fmap (map read.words)了用空格分割线,然后map read把每一个变成一个Int.Int由于类型签名,编译器知道我想要- 如果省略它我会收到错误.
| 归档时间: |
|
| 查看次数: |
2875 次 |
| 最近记录: |