There is a recent addition called OrderlessPatternSequence
that adds orderless matching for non-Orderless symbols. I am wondering if there is the exact opposite of this. For example:
ReplaceList[a + b + c, (m : Repeated[_, {2}]) + ___ -> {m}]
evaluates to
{{b, c}, {a, c}, {a, b}}
Is there any way to modify the pattern such that only consecutive terms match like so:
{{b, c}, {a, b}}
It is possible to first convert the Plus
to a non-Orderless List
, but I am interested in only changing the pattern expression. This allows for defining efficient downvalues that can take advantage of the automatic sorting of Orderless expressions. To take one example, imagine we are defining our own algebra and we want to define a rule that combines like terms automatically. Automatic orderless sorting encourages like terms to be nearby:
In[27]:= myOrderless[b, c, 5*b, c^2, -1*b, a, 5 b*c]
Out[27]= myOrderless[a, -b, b, 5 b, c, 5 b c, c^2]
For long expressions, this will take O(n^2) time if we do not assert consecutive pairs. Otherwise it can be O(nlogn). Another example would be defining a rule that operates on duplicates. We would always want our patterns to take advantage of the presort for efficient matching.
Partition[List @@ (a + b + c), 2, 1]
$\endgroup$