Understanding bound and free variables in LISP

二次信任 提交于 2019-12-10 19:29:35

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/31630769/understanding-bound-and-free-variables-in-lisp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!