haskell - Haskell 中有用的 ReadLn

标签 haskell io functional-programming

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/

相关文章:

haskell - 顺序的乐趣

scala - 通过 Free Monad 和 Coproduct 自动选择解释器

linux - linux中的api和设备文件有什么区别?

Java 子进程额外输出到控制台

list - haskell 。跟踪索引以生成新列表

scala - 理解纯功能性持久二叉树

haskell - Haskell 中遵守模态公理的有趣运算符

haskell - hamletFile、luciusFile、juliusFile 变量不在范围内

python - 程序文件目录中的 IO

scala - 将时间戳转换为间隔