Misunderstanding about closures
Alexander Schmolck
a.schmolck at gmx.net
Mon Jun 7 14:17:09 EDT 2004
"Michael Geary" <Mike at DeleteThis.Geary.com> writes:
> g = []
> def outer():
> x = 1
> def f():
> return x
> g.append( f )
> x = 2
> g.append( f )
>
> outer()
> print g[0](), g[1]()
>
> This prints:
>
> 2 2
> Now I am guessing that if you translated this code into any language that
> supports closures, including Scheme, you would get the "2 2" result, is that
> right?
Yep -- here's the scheme version.
(define g '())
(define (outer)
(let* ((x 1)
(f (lambda () x)))
(set! g (cons f g))
(set! x 2)
(set! g (cons f g))))
(outer)
(list ((car g)) ((cadr g)))
=> (2 2)
'as
More information about the Python-list
mailing list