简体   繁体   English

理解LISP中的绑定和自由变量

[英]Understanding bound and free variables in LISP

I'm reading SICP , and the topic of bound and free variables has come up. 我正在阅读SICP ,并且出现了绑定和自由变量的主题。 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? 所有这些都与范围有什么关系?

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: 记住, let是语法糖,所以它真的是这样的:

(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. 在内部lambda中, y作为绑定变量+x是自由的。 In the outer lambda x is bound and + is free. 在外部lambda x绑定, +是自由的。 + might be a global. +可能是一个全球性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM