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
- References:
- Bug in pattern test, or I did something wrong?
- From: Yi Wang <tririverwangyi@gmail.com>
- Bug in pattern test, or I did something wrong?