5 points · by kevinrose · 19y ago · 1 comment
(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