12

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?

Teake Nutma
  • 5,981
  • 1
  • 25
  • 49
  • 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 '14 at 18:41
  • Related Q: why does list //. {before___, 0, 1, after___} :> after only match the first instance? Whereas, {a, b, a} //. a :> z matches both instances of a – alancalvitti Apr 07 '18 at 04:35

1 Answers1

9

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.

Taliesin Beynon
  • 10,639
  • 44
  • 51
  • 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 '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 '14 at 03:10