Why is `2 + x = 7` valid Haskell?

  • A+
Category:Languages

When I try to compile

main = putStrLn $ show x where     2 + x = 7 

GHC complains

error: Variable not in scope: x   | 1 | main = putStrLn $ show x   |                        ^ 

So it seems that 2 + x = 7 is by itself syntactically valid, although it doesn't actually define x. But why is it so?


It is valid because it defines + instead.

main = putStrLn (3 + 4)    where -- silly redefinition of `+` follows    0 + y = y    x + y = x * ((x-1) + y) 

Above, the Prelude (+) function is shadowed by a local binding. The result will be 24, not 7, consequently.

Turning on warnings should point out the dangerous shadowing.

<interactive>:11:6: warning: [-Wname-shadowing]     This binding for ‘+’ shadows the existing binding 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: