       scope all wrong? in Mathematica 4.1

• To: mathgroup at smc.vnet.net
• Subject: [mg31827] scope all wrong? in Mathematica 4.1
• From: Richard Fateman <fateman at cs.berkeley.edu>
• Date: Wed, 5 Dec 2001 06:51:53 -0500 (EST)
• Organization: University of California, Berkeley
• Sender: owner-wri-mathgroup at wolfram.com

```Consider the mathematica definition

rr[x_] := Block[{x}, x = 5; Print["x is ", x]]

what do you expect here?

rr[z]  -->   x is 5  is printed.
but you might not expect

rr  -->    "Block::"lvsym": "Local variable specification{4} contains 4
which is not a symbol or an assignment to a symbol."

If you use Module instead of Block, you get
the same.

However,
Block[{x = 4}, Block[{x}, x = 5; Print["x is ", x]]]

prints   x is 5

Using pattern matching for
substituting 4 for x in rr even when x is bound seems
to be counter to what most programming language designers
would expect.

Now look at

uu[x_?((x = 5; Print["x is ", x]; True) &)] := x

Usually when one defines a program, nothing is printed.
Here, we get
x is 5
5
x is 5

If we do this:
x =400
uu
x is 5  printed
the value returned is 70
and the global x is 5.

Try this:
Module[{x}, uu[x_?((x = 5; Print["x is ", x]; True) &)] := x;
Print["in Module, x is " , x]]

The expectation in a system supporting lexical scope
with Module
is that no use of x inside the module would escape.
But it does.  The global x is set to 5.

The reason this all came up is in correspondence suggesting
that programs in one computer algebra system could be
translated into another.  If systems are semantically
"surprising", it is more difficult. I wonder how much
of mathematica internally depends on wrong scope, or how
much of the code is susceptible to bugs because of unexpected
capture of names.  (I suspect that this has caused a proliferation
of package names e.g. MySecretNameSpace`x   in Mathematica
routines).

RJF

```

• Prev by Date: Re: NDSolve problem
• Next by Date: Re: coloring eveerything outside a circle
• Previous by thread: WTB: Control Systems Professional for Mathematica 2.2 for the Macintosh
• Next by thread: Re: scope all wrong? in Mathematica 4.1