Reading — step 1 of 5
Read
Closures
A function that captures variables from its enclosing scope:
(define (make-counter)
(define count 0)
(lambda ()
(set! count (+ count 1))
count))
(define c (make-counter))
(c) ; 1
(c) ; 2
(c) ; 3
Each call to make-counter creates a NEW environment with a fresh count. The returned lambda captures THAT environment. Subsequent invocations remember/update the captured count.
Implementation requires environments to be FIRST-CLASS — they're real objects that lambdas hold references to.
set! modifies an EXISTING binding (vs define which creates new). For closures, set! modifies the CAPTURED env's binding.
This is also how garbage collection comes in: as long as the closure exists, its captured env is reachable and won't be collected. When the closure dies, the env can.
Closures + first-class functions = a complete computational basis (lambda calculus). Anything you can compute, you can express with these primitives.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…