NFC.cool
NFC.cool

Reputation: 3303

Use of accumulator in main

I want to use an accumulator in the main.

Lets say:

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

So what I want to do is if the user did not supply his name and just the age, I want to use the age that was entered before in the next main call. Any suggestion how I can achieve that?

Thanks

Upvotes: 0

Views: 83

Answers (1)

Random Dev
Random Dev

Reputation: 52270

sure just use another function where you can use arguments of your choice:

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 ""

allow me to introduce a small improvement: you probably don't want the infinite loop here - you can get rid of it easily using 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

this will stop the loop as soon as the user does not give his name

Upvotes: 3

Related Questions