> (let ((foo 1)) ; foo is lexical
> (define (bar n) (+ foo n))
> (bar 2) ; => 3
> (set! foo 2)
> (bar 2)) ; => 4
(Naturally, if instead of set! you do (let ((foo 2)) ...), it gives 3 again. But that's creating a new lexical scope, whereas in your example both definitions of foo are in the same scope, as is the definition of bar. I think.)OTOH,
> (define (bar n) (+ foo n))
> (let () ; create a new lexical scope
> (define foo 1)
> (bar 2)) ; error: unbound variable 'foo'
My understanding of dynamic variables is that bar would see the value of foo just defined, and return 3. Am I confused?(Tested with guile 1.6.7, which I gather is pretty old. Maybe that's the problem?)
edit: tested this in perl as well, with local to create dynamic variables.
sub bar { print($foo + shift(), "\n"); }
sub a { my $foo = 1; bar(2); }
a(); # prints 2, or errors if use strict is on.
sub b { local $foo = 1; bar(2); }
b(); # prints 3.