[gambit-list] dynamic scope
Marc Feeley
feeley at iro.umontreal.ca
Sun Feb 1 00:05:49 EST 2009
On 31-Jan-09, at 11:44 PM, lowly coder wrote:
> Great, the following works:
>
> cat test.scm
> (define (foo x) (* x 2))
>
> (define (g x) (foo x))
>
>
> (pp (g 2))
> (pp
> (let ((old-func '()))
> (dynamic-wind
> (lambda ()
> (set! old-func foo)
> (set! foo (lambda (x) (* x 3))))
> (lambda () (g 2))
> (lambda () (set! foo old-func)))))
>
> (pp (g 2))
>
> 4
> 6
> 4
>
> two questions:
> 1) can anything go wrong with variable capture / aliasing?
> [intuitively, I believe no, so long as I don't use 'old-func' in my
> thunk
> 2) is there a more elegant/idiomatic way to do this?
In terms of elegance I prefer this (which eliminates all variable
capture problems):
(let ((thunk (lambda () (g 2)))
(new-foo (lambda (x) (* x 3)))
(old-foo foo))
(dynamic-wind
(lambda () (set! foo new-foo))
thunk
(lambda () (set! foo old-foo))))
But once again this will not work right if multiple threads are
dynamically scoping foo simultaneously, but the parameterize based
approach will work fine.
Marc
More information about the Gambit-list
mailing list