动态作用域 - 深层绑定与浅层绑定

发布于 2024-08-11 18:06:43 字数 341 浏览 3 评论 0原文

我一直在尝试了解浅层绑定和深层绑定,维基百科并没有很好地正确解释它。 输出会是什么?

假设我有以下代码,如果该语言使用动态作用域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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

思慕 2024-08-18 18:06:43

深度绑定在过程作为参数传递时绑定环境浅度

绑定在实际调用过程时绑定环境

因此,当将 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.

青柠芒果 2024-08-18 18:06:43

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文