MathGroup Archive 2005

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

Search the Archive

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

  • To: mathgroup at smc.vnet.net
  • Subject: [mg56761] Re: [mg56696] named pattern variable scoped as global, should be local
  • From: DrBob <drbob at bigfoot.com>
  • Date: Thu, 5 May 2005 06:02:18 -0400 (EDT)
  • References: <200505040433.AAA06165@smc.vnet.net>
  • Reply-to: drbob at bigfoot.com
  • Sender: owner-wri-mathgroup at wolfram.com

Confusion is predictable, if you use the same symbol for the Module local variable and the pattern variable.

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

x in the pattern x_ has nothing to do with the local module variable x, so you have three different x variables -- global, local to the module, and local to the rule. x_ matches {1,2,3} and the right hand side is 2x (evaluated BEFORE the pattern variable has a value, so this is the module variable x, not the rule x). The Module returns 2x (x is undefined in the module) and popping out of the Module, x gets its global value.

In this example, the RHS of RuleDelayed is 2x, and it's evaluated AFTER the pattern variable has a value, so that's 2*{1,2,3}:

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

Almost the same thing happens here, but for a different reason (because q and x are different symbols):

Module[{x},{1,2,3}/.q_->2q]
{2,4,6}

2q evaluates to 2q before the Rule is applied, q_ matches {1,2,3}, and 2q becomes 2*{1,2,3}.

Bobby

On Wed, 4 May 2005 00:33:07 -0400 (EDT), <leenewman at gmail.com> wrote:

> 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
>
>
>
>



-- 
DrBob at bigfoot.com


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