Mathematica provides Alternatives, to match one of several patterns. In a rule, this is used as p1|p2|p3:>replacement. I would like to have the opposite logic: p1&p2&p3:>replacement (obviously using another notation) should match if all of p1, p2, and p3 match, and replacement should be allowed to involve variables in all of p1, p2, p3.
If one is simply concerned in whether all patterns match, one can use Except[Except[p1] | Except[p2] | Except[p3]], as described in Opposite of Alternatives or Logical AND of multiple patterns. I would like to do the same with rules, but the doubel-Except construction will not populate named patterns (at least in v10.0 I get an Except::named message).
Cases[{2/3, 1 + Pi, 3 - Gamma[I], 1 + x},
AndRuleDelayed[Plus[a_, b_], c_?NumericQ, {a, b, c}]]
(* should give
{{1, Pi, 1 + Pi}, {3, -Gamma[I], 3 - Gamma[I]}}
*)
FirstCaseto make it slightly more compact:AndRuleDelayed[patts__, rhs_] := (total_ :> With[{result = FirstCase[{Table[total, {Length[{patts}]}]}, {patts} :> rhs]}, result /; ! MissingQ@result]);. – Leonid Shifrin May 30 '16 at 21:29FirstCase. The only drawback is if for some reason the user wantsrhsto expand to aMissing[...]construction, which would be considered as a failed match. – Bruno Le Floch May 31 '16 at 13:47Tracethe solution I noticed that the pattern nametotalis changed tototal$. Could you explain why and how does that happen. Thanks – Basheer Algohi Jun 02 '16 at 02:23f[x_]:=(t:>x+t). Thenf[a]evaluates tot$_ :> a + t$. This renaming is useful so thatf[t]evaluates as expected to a rule that addst. However,f[t$]will evaluate to a rule that multiplies by 2. This leads to occasional bugs (name collisions) when several constructions lead Mathematica to add$to the same variable names. – Bruno Le Floch Jun 02 '16 at 13:41