MathGroup Archive 2001

[Date Index] [Thread Index] [Author Index]

Search the Archive

scope all wrong? in Mathematica 4.1

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[4]  -->    "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.

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[4] 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
x is 5

If we do this:
x =400
     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


  • 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