我想在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
所以我想要做的是如果用户没有提供他的名字和年龄,我想使用之前在下一次主要呼叫中输入的年龄。有什么建议我能做到吗?
由于
答案 0 :(得分:3)
确保只使用另一个可以使用您选择的参数的函数:
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 ""
请允许我介绍一个小改进:你可能不希望这里有无限循环 - 你可以使用unless轻松摆脱它:
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
一旦用户没有提供他的名字
,这将停止循环