2
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ Maybe Partition[List @@ (a + b + c), 2, 1] $\endgroup$ – m_goldberg Jul 13 '17 at 6:50
5
$\begingroup$

Possibly something like:

ReplaceList[a + b + c, Verbatim[Plus][___, x_, y_, ___] -> {x, y}]

{{a, b}, {b, c}}

$\endgroup$
  • $\begingroup$ Thanks! This was exactly what I was hoping for. $\endgroup$ – Cory Walker Jul 14 '17 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.