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

问题描述 投票:1回答:1

我想创建一个循环,它将在循环的每次迭代期间获取用户输入,即getLine。这是可能的在主要内部还是在参数传递中使用getLine函数或根本不使用?我对Haskell相对较新,而且我已经掌握了大部分内容,但我不确定。显然,模式匹配将用于退出,但我怎样才能获得用户输入。我试图自己解决这个问题,但每次都失败了。提前致谢。

haskell function-call
1个回答
4
投票

你必须使用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

© www.soinside.com 2019 - 2024. All rights reserved.