MathGroup Archive 2003

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

Search the Archive

Scoping, named patterns, local vs global variables

  • To: mathgroup at smc.vnet.net
  • Subject: [mg44866] Scoping, named patterns, local vs global variables
  • From: frankeye at cox.net (Frank Iannarilli)
  • Date: Thu, 4 Dec 2003 03:04:25 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

Hi,


For context, refer to a 1999 group posting by Ted Ersek:

http://groups.google.com/groups?q=set+scoping+group:comp.soft-sys.math.mathematica&hl=en&lr=&ie=UTF-8&group=comp.soft-sys.math.mathematica&selm=7kho2v%24qmt%40smc.vnet.net&rnum=1

Summary punchline:

x=1;
f[x_]=x^2; 
In: f[3]
Out: 1  (and not 3^2=9, since x is global)


I'm sure I'm not alone in periodically getting burned by this
behavior.  One would think in Mathematica, the named pattern on the lhs would
behave as a locally scoped variable for the rhs, but not so if there's
a global variable of the same name lurking within the session.


For the long-timers, this is old news.  But then, why does this actual
behavior conflict with Wolfram's own longstanding documentation in The
Book, as the following snippets demonstrate?  (Perhaps revisions in
The Book are warranted in the next edition!)

  Quoting from The Book for Mathematica version 5:

     In 2.7.4 Advanced Topic: Variables in Pure Functions and Rules:

"Module and With allow you to give a specific list of symbols whose
names you want to treat as local. In some situations, however, you
want to automatically treat certain symbol names as local.

For example, if you use a pure function such as Function[{x}, x + a],
you want x to be treated as a "formal parameter", whose specific name
is local. The same is true of the x that appears in a rule like f[x_]
-> x^2, or a definition like f[x_] := x^2.

Mathematica uses a uniform scheme to make sure that the names of
formal parameters which appear in constructs like pure functions and
rules are kept local, and are never confused with global names."

..... then further on:

      "{lhs = rhs  and  lhs := rhs , local pattern names
}"

....  then further still:


"Mathematica treats transformation rules as scoping constructs, in
which the names you give to patterns are local. You can set up named
patterns either using x_, x__ and so on, or using x:patt. "


====>>>  Is there a proper "Mathematica way" of interpreting the above
to square with actual behavior?

Just wondering...
Cheers!


  • Prev by Date: Re: Re: How to NOT convert Sin[x]/Cos[x] to Tan[x] ?
  • Next by Date: Re: Mathematica 4.2 and Mandrake 9.2
  • Previous by thread: Re: For Loop
  • Next by thread: Re: Scoping, named patterns, local vs global variables