3

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:{} *)
LBushkin
  • 471
  • 3
  • 11

1 Answers1

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

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

See

Pattern matching a pattern with patterns

How to match a pattern with a pattern?

for some in-depth discussions on similar constructs.

ciao
  • 25,774
  • 2
  • 58
  • 139