Haskell - 如何创建一个包含 getLine 的循环?

Haskell - how do you make a loop that has getLine within it?

我想创建一个循环,在循环的每次迭代中获取用户输入,即 getLine。这是否可能在 main 中或通过在参数传递中使用 getLine 函数或根本不可能?我对 Haskell 比较陌生,我已经了解了其中的大部分内容,但我不确定这一点。显然模式匹配将用于退出它,但我怎么能得到用户输入。我试图自己解决这个问题,但每次都失败了。提前致谢。

您必须为您的函数使用 IO monad,为了创建一个循环,您只需进行一个递归调用,检查这个例子:

-- This just wraps the getLine funtion but you could operate over the input before return the final result
processInput :: IO String
processInput = do
    line <- getLine
    return $ map toUpper line


-- This is our main loop, it handles when to exit
loop :: IO ()
loop = do
    line <- processInput
    putStrLn line
    case line of
        "quit"    -> return ()
        otherwise -> loop

-- main is the program entry point
main :: IO ()
main = do
    putStrLn "Welcome to the haskel input example"
    loop

这里有 live example