MathGroup Archive 2012

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

Search the Archive

Re: Bug in pattern test, or I did something wrong?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg125889] Re: Bug in pattern test, or I did something wrong?
  • From: Bob Hanlon <hanlonr357 at gmail.com>
  • Date: Fri, 6 Apr 2012 05:53:33 -0400 (EDT)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com
  • References: <201204050951.FAA13156@smc.vnet.net>

ClearAll[f, g, a, x];

f[a_ /; MemberQ[{0, 1, 2}, a]] := 0;

f[x] /. f[expr_] :> f[-expr]

f[x]

The unexpected result arises because

{MemberQ[{0, 1, 2}, expr_], MemberQ[{0, 1, 2}, _]}

{True, True}

A blank (with or without a name) matches anything. This causes the LHS
of your rule to become zero. Consequently, you need to use HoldPattern
on the LHS to keep it from evaluating.

f[x] /. HoldPattern[f[expr_]] :> f[-expr]

f[-x]


f[x] /. f[expr_] + a_. :> f[-expr] + a

f[-expr] + f[x]

The LHS of the rule evalutes to 0 + a_. and then to a_. Consequently,
a is f[x] and you get what you asked for. Again, you need to keep the
LHS of the rule from evaluating.

f[x] /. HoldPattern[f[expr_] + a_.] :> f[-expr] + a

f[-x]


With g the LHS of the rule does not change and you get what you intended.


Bob Hanlon


On Thu, Apr 5, 2012 at 5:51 AM, Yi Wang <tririverwangyi at gmail.com> wrote:
> Hi, all,
>
> When I define a function using pattern test conditions, I got some unexpected Replace (or ReplaceAll) behaviour:
>
> ClearAll[f, g, a, x];
> f[a_ /; MemberQ[{0, 1, 2}, a]] := 0;
>
> f[x] /. f[expr_] :> f[-expr]
> (* expect f[-x], but I got f[x] *)
>
> f[x] /. f[expr_] + a_. :> f[-expr] + a
> (* Even worse, Here I got f[-expr] + f[x], completely weird! *)
>
> PS: Workaround: if I use another form of pattern test, there is no problem:
>
> g[a_?MemberQ[{0, 1, 2}, #] &] := 0;
> g[x] /. g[expr_] :> g[-expr]
>
> (* g[-x] as desired *)
>
> g[x] /. g[expr_] + a_. :> g[-expr] + a
> (* g[-x] as desired *)
>



-- 
Bob Hanlon



  • Prev by Date: Re: Evaluating Exponential functions
  • Next by Date: Re: How to generate ``nice'' algebra output from command-line mathematica?
  • Previous by thread: Re: Bug in pattern test, or I did something wrong?
  • Next by thread: Re: Bug in pattern test, or I did something wrong?