首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Haskell - Do while循环

Haskell - Do while循环
EN

Stack Overflow用户
提问于 2016-02-26 06:17:15
回答 2查看 12.1K关注 0票数 7

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

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

代码语言:javascript
复制
    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")
EN

回答 2

Stack Overflow用户

发布于 2016-02-26 06:33:22

在Haskell中,大多数情况下都是递归地编写“循环”。

代码语言:javascript
复制
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!"
票数 13
EN

Stack Overflow用户

发布于 2016-02-26 07:27:35

不确定,也许这个版本可以帮助你:

代码语言:javascript
复制
import Control.Monad

loop action = do
    condition <- action
    when condition (loop action)

while = return

start =
    let action = 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;
        while (goGlenn /= "start");
    }
    in loop action

(编辑)或也可以:

代码语言:javascript
复制
start =
    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;
        while (goGlenn /= "start");
    })        
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35639501

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档