I'm trying to write a rule that can rewrite a pattern that exists in another expression. For some reason, this is proving to be more challenging than I expected ... most likely because I'm not totally understanding how Mathematica implements its pattern matching mechanism.

Here's my simple test case:

foo = Foo[a: {A,B,C}, b: {a,b,c}]    (* FullForm yields: Foo[Pattern[a,A],Pattern[b,B]] *)

I want to rewrite the portion b : {a,b,c} with some other expression, like Reverse[<b>] which should yield: b : {c,b,a}.

Here's what I've tried to far (none of which works):

foo /. (b:X_) -> Reverse[X]                 (* #1 produces Foo[b: {a,b,c}, a: {A,B,C}] *)

foo /. Hold[(b : B_)] -> Reverse[B]         (* #2 no effect *)

foo /. HoldForm[(b : B_)] -> Reverse[B]     (* #3 no effect *)

foo /. HoldPattern[(b : B_)] -> Reverse[B]  (* #4 same as case #1 *)

foo /. (b : B_List) -> Reverse[B]           (* #5 reverses both a:{} and b:{} *)
  • $\begingroup$ You may also be interested in expression parsers. Two examples which come to mind are here and here (function depends). $\endgroup$ Commented Mar 13, 2014 at 11:01

1 Answer 1

foo /. HoldPattern[Pattern][Verbatim[b], x_] :> Pattern[b, Reverse@x]

(* Foo[a : {A, B, C}, b : {c, b, a}] *)


Pattern matching a pattern with patterns

How to match a pattern with a pattern?

for some in-depth discussions on similar constructs.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.