[plt-scheme] Newbie Schemer question

From: Anton van Straaten (anton at appsolutions.com)
Date: Wed Nov 6 01:48:14 EST 2002

> I would like to execute a function that has one of its variable defined
> outside this function, in an upper context. Suppose that I define a simple
> function such as:
>
> (define (f n)
>   (+ *p* n))
>
> I would like to write something like that (the following syntax is
> incorrect):
>
> ((let ((*p* 1))
>   (lambda ()
>     (f 2)))
>
> How should I formulate this in Scheme?

The feature you're describing is usually called "dynamic scope" or "dynamic
variables" (not to be confused with similar terms sometimes used in the
context of fluid-let).  Scheme does not support dynamic scope directly.
Since Scheme uses lexical scoping, as Paul pointed out, this doesn't work
because the body of the function f, where *p* is referenced, is not within
the same lexical scope as the definition of *p*.

Dynamic scope is generally considered a bad idea because it can make
programs hard to understand, and introduce bugs.  In any given lexical
scope, e.g. within a function, it's hard for a human reader of the code to
tell what variables may or may not be available in that scope, and the
available variables can change from one invocation of the function to the
next.

Still, there are situations in which something like dynamic scope can be
useful.  I assume your example is just a simplified version of what you
really want to do.  If you can explain what it is you're trying to do, I'm
sure an appropriate Scheme solution can be suggested.

Anton



Posted on the users mailing list.