1 comment

[ 3.0 ms ] story [ 17.2 ms ] thread
A cool aspect of closures not stressed in the video is that they end up capturing all enclosing lexical environments (not just the parameter environments), even those you make using let! For example in Common Lisp:

(let ((x 0)) (defun counter () (setq x (+ x 1)) x))

Or in Scheme:

(define counter (let ((x 0)) (lambda () (set! x (+ x 1)) x)))

You can make a closure named "counter" that has access to the environment containing "x" so that every time you call those functions they return the next "x".

If you really want to understand closures I recommend reading Section 3.2 of SICP [1] and learning how to draw environment diagrams.

[1] http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-21.html#%25_sec_3.2