动态作用域 - 深层绑定与浅层绑定
我一直在尝试了解浅层绑定和深层绑定,维基百科并没有很好地正确解释它。 输出会是什么?
假设我有以下代码,如果该语言使用动态作用域a) 深层绑定
b) 浅层绑定,
x: integer := 1
y: integer := 2
procedure add
x := x + y
procedure second(P:procedure)
x:integer := 2
P()
procedure first
y:integer := 3
second(add)
----main starts here---
first()
write_integer(x)
I've been trying to get my head around shallow binding and deep binding, wikipedia doesn't do a good job of explaining it properly. Say I have the following code, what would the output be if the language uses dynamic scoping with
a) deep binding
b) shallow binding?
x: integer := 1
y: integer := 2
procedure add
x := x + y
procedure second(P:procedure)
x:integer := 2
P()
procedure first
y:integer := 3
second(add)
----main starts here---
first()
write_integer(x)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
深度绑定在过程作为参数传递时绑定环境浅度
绑定在实际调用过程时绑定环境
因此,当将 add 传递到第二个过程时,可以使用深度绑定进行动态作用域
环境是 x = 1,y = 3,x 是全局 x,因此它将 4 写入全局 x,这是 write_integer 拾取的值。
浅绑定只会向上遍历,直到找到与该名称对应的最近的变量,因此答案为 1。
Deep binding binds the environment at the time the procedure is passed as an argument
Shallow binding binds the environment at the time the procedure is actually called
So for dynamic scoping with deep binding when add is passed into a second
the environment is x = 1, y = 3 and the x is the global x so it writes 4 into the global x, which is the one picked up by the write_integer.
Shallow binding just traverses up until it finds the nearest variable that corresponds to the name so the answer would be 1.
a) 在深度绑定中,我们处理 add 的环境,其中 x 指的是全局 x,y 指的是第一个局部的 y(最后一个执行的函数,其声明为 y)
x (全局) = x (全局) + y (local) : x = 1 + 3 = 4
b) 在浅绑定中,我们处理第二个环境,其中 x 指第二个局部的 x,y 指第一个局部的 y(最后一个)执行的函数,其声明为 y)
x (local) = x (local) + y (local) : x = 2 + 3 = 5
但是 : write_integer(x) 输出等于 1 的全局 x
最后
a) 4
b) 1
a) In deep binding we deal with the environment of add, in which x refers to the global x and y refers to the y local to first (the last executed function which has a declaration of y)
x (global) = x (global) + y (local) : x = 1 + 3 = 4
b) In shallow binding, we deal with the environment of second, in which x refers to the x local to second and y refers to the y local to first (the last executed function which has a declaration of y)
x (local) = x (local) + y (local) : x = 2 + 3 = 5
BUT : write_integer(x) outputs the global x which is equal to 1
Finally
a) 4
b) 1
浅绑定应为 5。
定义:
http://www.planet-source -code.com/vb/scripts/ShowCode.asp?txtCodeId=15&lngWId=6
shallow binding should be 5.
definations:
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=15&lngWId=6