Haskell endless loop with just repetitive action
I have code like this:
Prelude> let n = [1,2,3,4]
Prelude> n
[1,2,3,4]
Prelude> 0:n
[0,1,2,3,4]
Prelude> let n = 0:n
And when I type the Haskell interpreter after the top level:
Prelude> n
I am getting infinite result:
[0,0,0,0,0,0,0,0,0
And where the seal "0" is endless.
Why am I getting this result?
Is there some kind of recursive stuff and why / how does it work at the interpreter level?
Can I catch a stack overflow, what's on GHCi or not?
Thanks,
Best wishes!
What Josh says is that you define n as:
0:n. -- note n still equals 0:n, just like you said
0:0:n. -- note n _still_ equals 0:n
0:0:0:n
...
The new binding n
shades the old one. You don't reassign variables in Haskell.
Haskell let
is similar to letrec
other languages ββlike ML: bindings are allowed to be recursive. In other words, it n = 0:n
defines n
as a list, where the first element 0
is and the rest of the list is equal n
. This means the second element n
is equal to the first element n
, which is 0
, etc.
In Haskell, because of laziness, infinite lists are fine. If you only use the first 10 elements of the list, then the 11th element and subsequent ones will never be evaluated.