I've seen plenty of examples where main
calls a helper function that calls itself recursively, e.g.
main = loop
where
loop = do
putStrLn "I'm in a loop"
loop
I have never seen a case where main
calls itself recursively, e.g.
main = do
putStrLn "I'm in a loop"
main
It seems to work fine though, which leaves me wondering why I've never seen it. Is it considered non-idiomatic? Does it change something about the compiled program?
It's perfectly fine, but it's pretty uncommon that every part of your program is repeated indefinitely. Usually you have some one-time setup or something, and then you enter into a loop to execute the remainder; or you have some cleanup to do after the main loop finishes. In that case you can't call main
again, because it would do the one-time setup (or cleanup) every time. If you have no one-time setup, feel free to have main
call itself.
Since last call optimizations are a regular thing in Haskell, yes, that's completely fine. Learn You A Haskell includes some examples using this kind of recursion. Also, this StackOverflow's post digs a little deeper in this topic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With