lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Here's an example of a Scheme function capturing the state of its
environment at the point of closure, blocking further modification.

I've tried to replicate the conditions under which our example Lua
program showed sensitivity to environment change, although it's hard
to create exactly the same conditions in a purely functional program.

; ------------------------------------------------------------
; Demonstration of Scheme lexical scoping and function closure

; Gentle intro example without functions
(let* ((foo
     foo)                       ; prints 10

; Defines and applies function incfoo1 using free variable foo
(let* ((foo                     ; define foo
       (incfoo1                 ; define incfoo1
            (lambda () (+ foo 0.1)))
       (bar                     ; define bar
            65))                ; bar not used (just for symmetry)
     (incfoo1))                 ; prints 10.1

; Defines and applies function incfoo1 using free variable foo
; but overrides (foo 10) with (foo 20) before function is used.
(let* ((foo
            (lambda () (+ foo 0.1)))
            (let* ((foo         ; Let's change foo (as in Lua)
                       20))     ; to try to make incfoo1 use 20.
                  incfoo1))     ; Will this closure be affected?
     (incfoo2))     ; No, prints 10.1 because incfoo1 is a closure
                    ; which protects it against the change in foo
; ----------------------------------------------------------------

That was a bit of a quickie.  I'll try to find a closer approximation.

Rich Artym.
Existing media are so disconnected from reality that our policy debates
spin around a fantasy world in which the future looks far too much like
the past.