使用主蓄能器



我想在main中使用一个累加器。

比方说:

main = do
   putStrLn "Hey there, what's your name and age?"
   name <- getLine
   age <- getLine
   putStrLn ("Hi " ++ name ++ " you are " ++ age ++ " years old!")
   main

所以我想做的是,如果用户没有提供他的名字和年龄,我想在下一个主调用中使用之前输入的年龄。有什么建议我可以做到这一点吗?

感谢

一定要使用另一个可以使用您选择的参数的函数:

ask :: String -> IO ()
ask lastAge = do
   -- don't know what you want to do with lastAge
   -- so I just use it when the user did not enter anything
   putStrLn "Hey there, what's your name and age?"
   name <- getLine
   age' <- getLine
   let age = if null age' then lastAge else age'
   putStrLn ("Hi " ++ name ++ " you are " ++ age ++ " years old!")
   ask age
main :: IO ()
main = ask ""

请允许我介绍一个小的改进:你可能不想要这里的无限循环-你可以很容易地使用它,除非:

import Control.Monad (unless)
ask :: String -> IO ()
ask lastAge = do
   -- don't know what you want to do with lastAge but here you have it
   putStrLn "Hey there, what's your name and age?"
   name <- getLine
   unless (null name) $ do
     age' <- getLine
     let age = if null age' then lastAge else age'
     putStrLn ("Hi " ++ name ++ " you are " ++ age ++ " years old!")
     ask age

一旦用户没有给出自己的名字

,这将停止循环

相关内容

  • 没有找到相关文章

最新更新