读取终止条件的连续输入

时间:2016-08-24 23:32:33

标签: haskell

我对Haskell完全不熟悉。我正在编写代码以接受一系列值。

eg.
1 2
3 4
0 0

输入停止时的最后一个条件,我应该显示值1 2 3 4。

我已完成以下操作,但它不起作用。我需要一些帮助。

main = myLoop

myLoop = do inp <- getLine
            if (inp == "0 0") then
                putStrLn "END"
            else do putStrLn(inp)
                      myLoop

1 个答案:

答案 0 :(得分:4)

首先,确保您没有在源中使用制表符。为了让您的示例有效,我必须将putStrLnmyLoop排成一行:

myLoop = do inp <- getLine
            if (inp == "0 0") then
                putStrLn "END"
            else do putStrLn(inp)
                    myLoop
               --   ^ note putStrLn and myLoop are at the same column

其次,假设您想要阅读数字/单词列表,我会回答这个问题。

readNums :: IO [String]
readNums = do
  x <- getLine
  if x == "0 0"
    then return []
    else do xs <- readNums
            return (words x ++ xs)

使用示例:

main = do nums <- readNums
          print nums