Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2005
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

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: [mg56720] Re: [mg56696] named pattern variable scoped as global, should be local
  • From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
  • Date: Thu, 5 May 2005 06:01:06 -0400 (EDT)
  • References: <200505040433.AAA06165@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

On 4 May 2005, at 13:33, 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
>

To me this indeed looks like a bug, but Mathematica's scoping is 
strange and it is sometimes hard to tell what is a bug and what is a 
part of the design.

The reason why it looks to me like a bug is this:

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

{2,4,6}

besides this "workaround" I can see two other choices:

1. Use RuleDelayed:

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

2. Use Block instead of Module:

Block[{x},{1,2,3}/.x_->2x]

{2,4,6}


Andrzej Kozlowski
Chiba, Japan
http://www.akikoz.net/andrzej/index.html
http://www.mimuw.edu.pl/~akoz/


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