Skip to main content

replacement - Using PatternSequence on its own in ReplaceAll?



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?



Answer



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.


Comments