Hubble
Hubble

Reputation: 49

Lexical Binding in Lisp

(let ((a 3))
  (let ((a 4)
        (b a))
    (+ a b))) 

The above code evaluates to 7 the logic being that b takes the value of outer a. According to my understanding, in lexical binding each use of 'let' creates a fresh location. So why is the variable b in the statement (b a) not using the value of a from (a 4)?

Upvotes: 1

Views: 147

Answers (2)

Sylwester
Sylwester

Reputation: 48745

(let ((a 4)
      (b a))
  (+ a b)) ; ==> 7

Is equivalent to writing:

((lambda (a b)
   (+ a b))
 4
 a) ; ==> 7

Do you see from this version that it's logical that a and b are bound after the evaluation of 4 and a?

Now we have:

(let* ((a 4)
       (b a))
  (+ a b)) ; ==> 8

which is equivalent to:

(let ((a 4))
  (let ((b a))
    (+ a b))) ; ==> 8

Here the second let is in the body of the first. a is 4 when the expression for b is evaluated.

Upvotes: 1

Rainer Joswig
Rainer Joswig

Reputation: 139261

Because that's what LET is specified to do. Bindings are done in parallel.

CL-USER 60 > (let ((a 3))
               (let ((a 4)
                     (b a))
                 (+ a b)))
7

The version where bindings are done in a sequential fashion is called LET*.

CL-USER 61 > (let ((a 3))
               (let* ((a 4)
                      (b a))
                 (+ a b)))
8

See Special Operator LET, LET*.

Upvotes: 5

Related Questions