gpt4 book ai didi

haskell - Haskell 中有用的 ReadLn

转载 作者:行者123 更新时间:2023-12-02 07:29:37 26 4
gpt4 key购买 nike

Haskell 中是否有像 Pascal 中的 ReadLn 那样的内置函数?

我想要这样的东西:

λ> pascalReadLn :: IO (Int, Int, Int, Int)
1 2
3
4
(1,2,3,4)
λ> pascalReadLn :: IO (Int, Int, Int, Int)
1 2 3 4
(1,2,3,4)
λ> pascalReadLn :: IO (Int, Int, Int, Int)
1
2
3
4
(1,2,3,4)
...
etc.

最佳答案

你可以使用 ReadArgs 来解决这个问题

import ReadArgs

pascalReadLn :: ArgumentTuple a => IO a
pascalReadLn = pascalReadLn' ""
where pascalReadLn' lines = do
line <- getLine
let lines' = lines ++ line
-- see if we've read enough to successfully parse the desired tuple
case parseArgsFrom (words lines') of
Nothing -> pascalReadLn' (lines' ++ "\n")
Just a -> return a

它会根据有效输入的需要工作

λ pascalReadLn :: IO (Int, Int, Int, Int)
1 2
3
4
(1,2,3,4)
λ pascalReadLn :: IO (Int, Int, Int, Int)
1 2 3 4
(1,2,3,4)
λ pascalReadLn :: IO (Int, Int, Int, Int)
1
2
3
4
(1,2,3,4)

然而,它并不完美,因为它无法区分不完整的解析和不可能的解析:

λ pascalReadLn :: IO (Int, Int, Int, Int)
foo bar
1
2
3
4
... will go forever

自定义实现(与 ArgumentTuple 相同)可以通过区分两种失败情况来解决此问题,例如:

 data ParseResult a = Success a | Incomplete (String -> ParseResult a) | Impossible

class LineTuple a where
parseLine :: String -> ParseResult a

关于haskell - Haskell 中有用的 ReadLn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23282772/

26 4 0