Re: named pattern variable scoped as global, should be local

• To: mathgroup at smc.vnet.net
• Subject: [mg56765] Re: [mg56696] named pattern variable scoped as global, should be local
• From: "David Park" <djmp at earthlink.net>
• Date: Thu, 5 May 2005 06:02:47 -0400 (EDT)
• Sender: owner-wri-mathgroup at wolfram.com

```Lee,

This is a feature of Mathematica. You get a similar problem with Set and
SetDelayed when the right hand side of a definition has values.

The problem goes away if you use RuleDelayed.

x = 7;
Module[{x}, {1, 2, 3} /. x_ :> 2x]
{2, 4, 6}

If we use a plain Rule and Trace the evaluation, you can see what happens.

x = 7;
{Module[{x}, {1, 2, 3} /. x_ -> 2 x], {{{{x, 7}, 2 7, 14},
x_ -> 14, x_ -> 14}, {1, 2, 3} /. x_ -> 14, 14}, 14}

The rhs of the rule is evaluated to 14. Then the pattern x_ matches the
entire list and replaces it by 14.

I generally avoid giving values to single letter symbols like x since we so
often want to use them symbolically. That way you aren't forced to used
SetDelayed and RuleDelayed as often. You can always define Rules to give
values to symbols like x when you want to.

David Park

From: leenewman at gmail.com [mailto:leenewman at gmail.com]
To: mathgroup at smc.vnet.net

When using a named pattern variable within a module, it should be
scoped locally within the pattern.  However, this does not seem to work
as advertised.  For example, shouldn't the pattern variable x in the
statements below be local to the pattern?  Does anyone know whether
this is a bug, or whether I am just missing something about the usage
of variables in patterns/condition constructs?

(* this returns 14! *)
x = 7;
Module[{x},{1, 2, 3} /. x_ -> 2x];

(* this returns {2,4,6}, assuming q is not globally defined. *)
Remove[q];
Module[{q},{1, 2, 3} /. q_ -> 2q];

Lee

```

• Prev by Date: Re: Cases and Nonatomic expression
• Next by Date: Re: letrec/named let
• Previous by thread: Re: named pattern variable scoped as global, should be local
• Next by thread: Re: named pattern variable scoped as global, should be local