Is this legal Haskell code?

GHC compiles it without a hitch, but it fails at runtime:

many_a x =
        a = 2
            a = 2*a


Intuitively, this shouldn't work. Yet the GHC accepted it.


source to share

1 answer

Yes, this is valid Haskell code. The point is that a

the second expression is

actually new a

; it is perfectly acceptable to shadow existing variables by defining a new variable with the same name. However, this does not affect the meaning of the external a

. However, it was generally considered bad because of the potential for confusion and error; if you pass -Wall

to the GHC it issues a warning if you do.

It "crashes" at runtime because you defined a

as 2*a

, which results in an infinite loop at runtime. This is due to laziness; basically, (*)

evaluates both arguments before multiplying them. Evaluation 2

works great, of course, but evaluation a

forces him to go through the same process over and over. The same thing that allows infinite lists (for example ones = 1:ones

) makes this code an infinite loop.



All Articles