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
  • 30,661
  • 4
  • 57
  • 106
abelard2008
  • 1,984
  • 1
  • 20
  • 35

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
  • 232,561
  • 37
  • 312
  • 386
  • @abelard20008 My pleasure! welcome to Stack Overflow, please remember to accept the answer that was most helpful for you, by clicking on the check mark to its left. – Óscar López Jul 01 '12 at 16:00
  • can I think that x in second function is a local variable? thanks – abelard2008 Jul 01 '12 at 16:24
  • @abelard20008 absolutely, that's what it is: a variable local to each invocation of the function, whereas in the first function `x` is shared by all invocations of the function – Óscar López Jul 01 '12 at 16:28
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
  • 61,765
  • 13
  • 122
  • 144
  • 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,036
  • 1
  • 15
  • 29
  • 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