I need a loop for main in Haskell. I’ve tried this:
main :: IO ()
main =
do
putStrLn "do something"
main
Is the above code the correct approach to take? Will this infinite recursion cause an overflow?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is fine; no stack overflow will occur. Stack overflows in Haskell (and, indeed, any non-strict language) are different to those in other languages; they arise from accumulating large values without ever evaluating them, but you’re not accumulating anything here; just sequencing an infinite chain of actions. You can think of it like this: Once the line is printed, the action is discarded, and control passes straight onto
main; nothing is kept on the stack because there’s nothing that has to be returned to.It’s the same reason you can iterate through an infinite list without running out of memory: as the program goes further down the list, previous list cells are reclaimed by the garbage collector as they’re no longer required. In this case, the previous sequencings are reclaimed, as there’s no reason to keep around an action you’ve already performed.
That said, a nicer way to write this particular example is:
Of course, this won’t work if your loop is ever intended to terminate.
foreveris itself implemented with recursion, so there’s no benefit other than readability to doing this.