Haskell - 做循环

Has*_*oob 5 haskell while-loop do-while

我是Haskell的新手,如果有人愿意帮助我,我会很高兴的!我试图让这个程序与do while循环一起工作.

第二个getLine命令的结果被放入varible goGlenn,如果goGlenn不等于"start",那么程序将返回到开头

    start = do
    loop $ do lift performAction
        putStrLn "Hello, what is your name?"
        name <- getLine
        putStrLn ("Welcome to our personality test " ++ name ++ ", inspired by the Big Five Theory.") 
        putStrLn "You will receive fifty questions in total to which you can reply with Yes or No."
        putStrLn "Whenever you feel ready to begin please write Start"
        goGlenn <- getLine
        putStrLn goGlenn
    while (goGlenn /= "start")
Run Code Online (Sandbox Code Playgroud)

chi*_*chi 11

在Haskell中,你大多数时候递归地写"循环".

import Control.Monad

-- ....

start = do
    putStrLn "Before the loop!"
    -- we define "loop" as a recursive IO action
    let loop = do
            putStrLn "Hello, what is your name?"
            name <- getLine
            putStrLn $ "Welcome to our personality test " ++ name 
                     ++ ", inspired by the Big Five Theory."
            putStrLn "You will receive fifty questions in total to which you can reply with Yes or No."
            putStrLn "Whenever you feel ready to begin please write Start"
            goGlenn <- getLine
            putStrLn goGlenn
            -- if we did not finish, start another loop
            when (goGlenn /= "start") loop
    loop  -- start the first iteration 
    putStrLn "After the loop!"
Run Code Online (Sandbox Code Playgroud)

  • 我猜OP正在尝试使用[`loop-while`](http://hackage.haskell.org/package/loop-while-1.0.0/docs/Control-Monad-LoopWhile.html)(参见与代码摘录相似).查看导入列表会有所帮助. (2认同)
  • 而不是写`let loop = ...; loop`,我喜欢写`fix $ \ loop-&gt; ...`。当然,这纯粹是风格。 (2认同)