No compiler warning on infinite loop on identity variable thunk?
import System.IO
main = let x = x in putStrLn x
For context, I started picking up Haskell about a month or two ago. I recently tried to write some code where I was setting x' to x but forgot the ' and I proceeded to enter an infinite loop that I could hardly see.
I was wondering why the compiler didn't warn me about this? Is there a case where this isn't incredibly dumb?
Also, why doesn't this blow the stack? Is it technically a case of tail recursion elimination? Or will it blow the stack and I just didn't run it for long enough?
Posted Apr 21, 2015, 12:53 AM UTC
22
The compiler doesn't warn you because that is perfectly legal Haskell, and it cannot detect infinite loops in general, so there will always be things it cannot detect. Sometimes self-referential expressions like
let x = 1:x in xare exactly what you want.You don't run out of memory in this case because you are not building up a large expression in memory. It doesn't get any larger than a single thunk (
x) so it doesn't use up extra space. (I'm not actually very knowledgeable when it comes to ghc internals, so someone can correct me.)Thanks for your answer! Your first bit really makes a lot of sense.
As for the second bit, I thought of it as trying to force x, which means evaluating the thunk x, which forces x recursively. I guess since the result is purely in the result of the evaluation of x, we don't need to build up the expression, like you said.
Thanks! This really helped me reason with my situation.