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 matching a pattern with Repeated (..) How can I use the repeat count in the replacement rule?

Example:

 Cases[ { {0, 2, 2, 5, 2, 4, 1, 2}, {0, 1, 2, 3, 4, 5}} ,
     {0, Repeated[x_ /; x != 5], 5, __} :> {0, Sequence @@ Table[x, {2}], 5}]
                                                                     ^ <---?

{{0, 2, 2, 5}}

Obviously instead of hard coding the 2 I want the length of the repeat..

My workaround for this example is this:

 #[[;; First@First@Position[#, 5]]] & /@
     Cases[ { {0, 2, 2, 5, 2, 4, 1, 2}, {0, 5, 5, 1, 2, 3, 4, 5}} ,
       {0, Repeated[x_ /; x != 5], 5, __} ]

{{0, 2, 2, 5}}

It seems there should be a cleaner solution though.

share|improve this question
3  
Use named patterns: Cases[{{0, 2, 2, 5, 2, 4, 1, 2}, {0, 1, 2, 3, 4, 5}}, {0, rep : Repeated[x_ /; x != 5], 5, __} :> {0, rep, 5}]. –  Leonid Shifrin Apr 25 at 16:00
    
Thanks! Maybe this should be closed if you think it too simple. –  george2079 Apr 25 at 16:05
2  
I don't have a strong opinion here. It may be simple for those who used this many times, but I bet many people might have such questions. And, the fact that a 5K rep user bothered to ask it may mean that it is not trivial at the very least. Let's wait what others think. –  Leonid Shifrin Apr 25 at 16:06
    
On second thought, I actually think we should keep this one - it is a nice example of more complex patterns, where one really does need two pattern variables, one for the entire pattern and another one to restrict its parts. –  Leonid Shifrin Apr 25 at 16:53

1 Answer 1

Just so this doesn't sit unanswered, per @LeonidShifrin comment:

 Cases[{{0, 2, 2, 5, 2, 4, 1, 2}, {0, 1, 2, 3, 4, 5}},
     {0, rep : Repeated[x_ /; x != 5], 5, __} :> {0, rep, 5}]

or : {0, rep : x_ .. /; x != 5 , 5, __}

For completeness if you literally wanted to use the form in the question:

 Cases[{{0, 2, 2, 2, 5, 2, 4, 1, 2}, {0, 1, 2, 3, 4, 5}},
         {0,rep : Repeated[x_ /; x != 5], 5, __} :>
         {0,Sequence @@ Table[ x, {Length@List@rep}], 5}]
share|improve this answer
1  
so as not to give readers the impression that Repeated picks out the sub-expression ,2,2, because it contains repeated two's, it might be useful to generalise to: Cases[{{0,2,2,5,2,4,1,2},{0,1,2,3,4,5}},{0,pat: x_ ..,y_,__}:>{0,pat,y}/;Length[{pat}]>1] or, in alternative form: Cases[{{0, 2, 2, 5, 2, 4, 1, 2}, {0, 1, 2, 3, 4, 5}}, {0, rep : Repeated[x_ /; x != 5, {2, \[Infinity]}], y_, __} :> {0, rep, y} ] –  Wouter Apr 26 at 17:11
    
for my application I intended the basic "one or more" meaning of Repeated –  george2079 Apr 28 at 19:20

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.