理解LISP中的绑定和自由变量(Understanding bound and free variables in LISP)

我正在阅读SICP ,并且出现了绑定和自由变量的主题。 但是,我很困惑。 术语“绑定变量”是否仅适用于作为形式参数的变量? 此外,文本说过程定义“绑定”其形式参数。 这让我感到困惑的是,有些人说我们将一个值“绑定”到一个变量上。 显然,当我们讨论不同类型的变量时,这个术语似乎意味着不同的东西。 有人可以清除绑定变量是什么以及绑定意味着什么? 最后,与绑定变量相比,什么是自由变量? 所有这些与范围有何关系?

I'm reading SICP, and the topic of bound and free variables has come up. However, I am confused about it. Does the term "bound variables" only apply to variables that are formal parameters? In addition, the text says that a procedure definition "binds" its formal parameters. This confuses me with the fact that some people say that we "bind" a value to a variable. Obviously, the term seems to mean different things when we're talking about different types of variables. Could someone clear up what a bound variable is and what binding means? Finally, in contrast to a bound variable, what is free variable? How does all of this relate to scope?

最满意答案

只有两种类型的变量。 全球性和词汇性。 实际上,您可以将全局视为词法范围的可变根,并且在这种情况下,只有一种类型的变量。

绑定变量是当前过程的形式参数,其他一切都是全局的,或者是从先前的嵌套调用绑定的,是自由变量。

例:

(lambda (x) (let ((y (+ x x))) ; + is free x is bound (+ x y))) ; + and x is free, y is bound

记住, let是语法糖,所以它真的是这样的:

(lambda (x) ((lambda (y) (+ x y)) ; + and x is free, y is bound (+ x x))) ; + is free x is bound

在内部lambda中, y作为绑定变量+和x是自由的。 在外部lambda x绑定, +是自由的。 +可能是一个全球性的。

There are only two types of variables. Global and lexical. You can actually think of global as a changeable root of the lexical scope and in that case there is only one type of variables.

A bound variable is the formal parameters of the current procedure and everything else, which either is global or bound from previous nested calls, are free variables.

Example:

(lambda (x) (let ((y (+ x x))) ; + is free x is bound (+ x y))) ; + and x is free, y is bound

Remember let is ust syntactic sugar so it's really the same as this:

(lambda (x) ((lambda (y) (+ x y)) ; + and x is free, y is bound (+ x x))) ; + is free x is bound

In the inner lambda with y as bound variable + and x are free. In the outer lambda x is bound and + is free. + might be a global.

更多推荐