简体   繁体   中英

Understanding bound and free variables in LISP

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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