Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: ok to recursively call main?

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?

like image 550
ivan Avatar asked Sep 17 '19 17:09

ivan


Video Answer


2 Answers

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.

like image 91
amalloy Avatar answered Sep 18 '22 13:09

amalloy


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.

like image 31
lzbernardo Avatar answered Sep 18 '22 13:09

lzbernardo