当我尝试编译
main = putStrLn $ show x where
2 + x = 7
Run Code Online (Sandbox Code Playgroud)
GHC抱怨
error: Variable not in scope: x
|
1 | main = putStrLn $ show x
| ^
Run Code Online (Sandbox Code Playgroud)
所以它似乎2 + x = 7本身在语法上是有效的,虽然它实际上没有定义x.但为什么会这样呢?
chi*_*chi 69
它是有效的,因为它定义了+.
main = print (3 + 4)
where -- silly redefinition of `+` follows
0 + y = y
x + y = x * ((x-1) + y)
Run Code Online (Sandbox Code Playgroud)
上面,Prelude (+)函数被本地绑定所遮蔽.结果将是24,而不是7.
打开警告应该指出危险的阴影.
<interactive>:11:6: warning: [-Wname-shadowing]
This binding for ‘+’ shadows the existing binding
Run Code Online (Sandbox Code Playgroud)
mel*_*ene 37
您正在定义一个名为的本地函数+.
2 + x = 7相当于(+) 2 x = 7,相当于
(+) y x | y == 2 = 7
Run Code Online (Sandbox Code Playgroud)
x是一个(未使用的)参数,只有在第一个参数为的情况下才定义该函数2.这不是很有用,但它解释了为什么x外面不可见.