Me envisioning closures in Scheme

By chr15t0ph

Closure (computer science): an abstraction binding a function to its scope.

Keywords: scope, binding of name to location or value, enclosed variable, mutating existing bindings

(define (factory1a) (let ((myBound 5)) (lambda (x) (set! myBound (+ myBound x)) myBound) ))
(define (factory1b) ((lambda (myBound) (lambda (x) (set! myBound (+ myBound x)) myBound) ) 5) )
(define closure1a (factory1a))
(define closure1b (factory1b))
(define closure2 (factory1a))
(print „comp.lang.functional: Closures are a big deal in a non-pure functional language, because mutable closed-over lexical variables can model an encapsulated mutable state. That’s how Scheme has started.“)
(newline)
(closure1a 0) ; => 5
(closure1b 0) ; => 5
(closure2 0) ; => 5
(closure1a 1) ; => 6
(closure1b 1) ; => 6
(closure2 18) ; => 23
(closure1a 2) ; => 8
(closure1b 2) ; => 8
(closure2 19) ; => 42

(define (factory2) (let ((myBound 0)) (lambda (x) (/ x myBound)) )) ; if evaluated it will always result in a division-by-zero error
(define closuresAreFirstOfAllLazyAndSetBangDoesNotMatter (factory2))
(print „closure is executed“)
(newline)

(closure1a 0) ; => still 8 („myBound“ of factory2 is not the same as of factory1 and its derived closures)
(closure2 0) ; => still 42
(closuresAreFirstOfAllLazyAndSetBangDoesNotMatter 23) ; => division-by-zero error

Eine Antwort schreiben