1
  1. (define self-add
    (let ((x 0))
      (lambda ()
        (set! x (+ x 1))
        x)))
    

(self-add) => 1

(self-add) => 2

(self-add) => 3

(self-add) => 4

    2.
 (define self-add1
    (lambda ()
      (let ((x 0))
        (set! x (+ x 1))
        x)))

(self-add1) => 1

(self-add1) => 1

(self-add1) => 1

Please tell me how to understand the difference between the above two functions? Thanks a lot in advance! Best regards.

soegaard
  • 29,570
  • 4
  • 55
  • 101
abelard2008
  • 1,764
  • 1
  • 17
  • 33

3 Answers3

5

The first function defines a local variable x with an initial value of 0 and afterwards binds a lambda special form to the name self-add - so x is "enclosed" by the lambda (that's why we say that the lambda from behaves as a closure) and will be the same for all invocations of self-add (you could say that x is "remembered" by self-add), and each time it gets called the value of x will be incremented by one.

The second function binds the lambda to the procedure and afterwards defines a local variable x inside the lambda - here x is redefined each time self-add1 gets called, and will be different for all invocations: so x is never "remembered" by self-add1 and is created anew every time the procedure gets called, initialized with 0 and then incremented, always returning the value 1.

Óscar López
  • 225,348
  • 35
  • 301
  • 374
1

The first function is closure. You create x variable in the lexical scope of the function and the variable holds its value between calls.

Additional information:

Community
  • 1
  • 1
Igor Chubin
  • 57,130
  • 8
  • 114
  • 135
  • where to get the knowledge about Scheme's closure, I didn't find anything about in book "The Scheme programming language 4th edition",Thanks ! – abelard2008 Jul 01 '12 at 15:36
0

First function is a closure, while second function simply returns the same function every time, which makes x = 0 and then adds one and returns the result.

Mateusz Kowalczyk
  • 2,016
  • 1
  • 14
  • 28
  • where to get the knowledge about Scheme's closure, I didn't find anything about in book "The Scheme programming language 4th edition",Thanks ! – abelard2008 Jul 01 '12 at 15:29
  • I recommend that you read [SICP](http://mitpress.mit.edu/sicp/). It's free and a very good Computer Science book that happens to be using Scheme. It covers usage of closures as well. Good luck. – Mateusz Kowalczyk Jul 01 '12 at 17:31