Wesley
Wesley

Reputation: 1237

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?

Upvotes: 4

Views: 1134

Answers (1)

Sylwester
Sylwester

Reputation: 48745

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.

Upvotes: 5

Related Questions