Misunderstanding about closures

Alexander Schmolck a.schmolck at gmx.net
Mon Jun 7 07:06:43 EDT 2004


"Michael Geary" <Mike at DeleteThis.Geary.com> writes:

> Alexander May wrote:
>> When I define a function in the body of a loop, why doesn't the
>> function "close" on the loop vairable?  See example below.
>
> Hi Alex,
>
> Your message title is correct: you're misunderstanding how closures work.
> :-)

Not necessarily. See below.

[snipped]

> BTW, you'll see the same effect in JavaScript or any other language that
> supports closures.

Not quite. In fact in the language that more or less started it all, scheme,
the standard iteration construct 'do' does indeed introduce a *new binding* on
each iteration.


;; Note: this is is a literate translation and *not* idiomatic scheme -- no
;; schemer would write it like that
(define l '())                       ; an empty list

(do ((x 0 (+ 1 x)))                  ; start x with 0, then add 1 at each step
    ((= x 10))                       ; stop when x is 10
  (set! l (cons (lambda () x) l)))        ; add a new function closing over x to
				     ; the *front* of l

(set! l (reverse l))                 ; since we added to the front we 
                                     ; have to reverse l

((list-ref l 3))                     ; get list element 3 and execute it
> 3                                  ;ANSWER


Common Lisp OTOH doesn't -- like python:

;; This is similarly non-idiomatic (and won't work in emacs lisp, which hasn't
;; got lexical scope)
(defvar l '())                       ; an empty list

(do ((x 0 (+ 1 x)))                  ; start x with 0, then add 1 at each step
    ((= x 10))                       ; when x is 10 return the reversed list
  (setf l (cons (lambda () x) l)))        ; add a new function closing over x to
				     ; the *front* of l

(setq l (reverse l))                 ; since we added to the front we 
                                     ; have to reverse l

(funcall (nth 3 l))                  ; get list element 3 and execute it
> 10







More information about the Python-list mailing list