[plt-scheme] Scopes and closures

From: James Coglan (jcoglan at googlemail.com)
Date: Mon Jan 19 09:23:40 EST 2009

> 1. Is the following program in HtDP Beginning Student sufficient to
> show the difference between dynamic and static scope?
> -----------
> (define n 5)
> (define (f x)
>  (+ x n))
> (define (g n)
>  (f 3))
> -----------
> If I'm reasoning correctly, with static scope, f is saved with its
> closure, so n is forever bound to 5 and g applied to anything will
> always return 8. In dynamic scope, n would get its value from the
> argument passed into g. So,
> (g 7) --> 8 = static scoping
> (g 7) --> 10 = dynamic scoping

Yes that's right. Static scope means that functions defer to their lexical
context to find free variables (variables not in the function's parameter
list), whereas dynamic scope means they defer to the context in which they
are called.

2. In creating a closure, it's really only necessary to save values
> that the function uses, rather than the whole context

I'd be interested to know if you can in general do static checking on
closures to free up memory. I'm doing an implementation in Ruby, having only
just started learning Scheme. Right now, each function call creates a symbol
table that inherits from the scope in which the function is defined, and
definitions retain a reference to the current scope. That way, returning a
lambda from a function keeps a reference to the symbol table in use inside
the outer function, but I'm not doing any clean-up on it right now as I
don't know what errors that might cause further down the line.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20090119/27ed2c13/attachment.html>

Posted on the users mailing list.