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.

Say I have this list:

list = {0, 1, 2, 0, 1, 3, 0, 1, 4}

and say I want to remove consecutive sequences of 0 and 1. I'd normally go for this:

list //. {before___, 0, 1, after___} :> {before, after}
{2,3,4}

But a more concise way would be the following:

list /. PatternSequence[0, 1] -> Sequence[]

Alas, this doesn't do anything. The examples in the PatternSequence documentation are all of the form

list //. {before___, PatternSequence[0, 1], after___} :> {before, after}

which kind of defeat the purpose. (It's pretty useful if you want to name the PatternSequence on the LHS of the rule, but that's not my aim).

So the question is, is there a way to use constructs like PatternSequence[0, 1] -> Sequence[] in ReplaceAll?

share|improve this question
2  
My impression so far has been that the main advantage of PatternSequenceis that now one can name sequences of patterns for restructuring. This is an important feature, but is not the same as what you are looking for. –  Leonid Shifrin Jul 14 at 18:41

1 Answer 1

up vote 6 down vote accepted

You cannot do what you are trying to, unfortunately.

As Leonid says, PatternSequence is for grouping purposes. And in general the WL pattern matcher is not geared for "sequence-based patterns" for a whole variety of reasons. At a fundamental level the pattern matcher uses a 'cursor' that is always rooted at the level of an entire expression, and sequences are matched within that expression, rather than the 'cursor' itself being a sequence.

For example, expr //. {a___, 0, 1, b___} :> {a, b} takes $O(n^2)$ time in the length of the list, when it really could be $O(n)$, if we had better ways of describing and using sequence-based patterns.

What we really need is one or two functions with the same semantics as the String* functions, except that they operate on lists of expressions rather than strings of characters.

I do think that PatternSequence could be re-used in this context.

share|improve this answer
    
Thanks for the explanation. Keeping my fingers crossed for future versions then :). Is there any chance the documentation can be expanded a bit on this point? (I searched, but couldn't find anything). –  Teake Nutma Jul 14 at 20:51
2  
Solve it elegantly and in O(n) is a old unsolved MMA operation. The string parallel is perfect. +1 –  Murta Jul 15 at 3:10

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.