Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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:{} *)
share|improve this question
    
You may also be interested in expression parsers. Two examples which come to mind are here and here (function depends). –  Leonid Shifrin Mar 13 at 11:01

1 Answer 1

up vote 4 down vote accepted
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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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