gpt4 book ai didi

haskell - 如何在haskell的一行中输入多个值

转载 作者:行者123 更新时间:2023-12-03 14:39:14 25 4
gpt4 key购买 nike

例如,我想编写一个程序,它将从命令行输入 3 个整数。我学到的函数是readLn从整行读取值。但是readLn似乎将整行解析为单个值。如何使用haskell获得一行的三个值?

最佳答案

阅读一行 getLine ,将其拆分为 words , 和 read每个:

readInts :: IO [Int]
readInts = fmap (map read.words) getLine

它读取任意数量的 Int:
ghci> readInts
1 2 3
[1,2,3]
ghci> readInts
1 2 3 4 5 6
[1,2,3,4,5,6]

您可以限制为三个:
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

看起来像这样:
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
fmap的 secret
fmap有点像 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!"]

getInts ,我做了 fmap (map read.words)按空格分割行,然后 map read把每一个变成一个 Int .编译器知道我想要 Int由于类型签名 - 如果我省略它,我会得到一个错误。

关于haskell - 如何在haskell的一行中输入多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21885530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com