Wolfram Research

Function Repository Resource:

SimplifyRepeatedSubexpressions

Source Notebook

Replace repeated subexpressions in an expression with new symbols

Contributed by: Jon McLoone

ResourceFunction["SimplifyRepeatedSubexpressions"][expr]

returns a list of the expr with repeated subexpressions removed, along with the replacement rules used to rewrite them in simpler form.

Examples

Basic Examples

Find the repeated term in the expression (a+b+c)3+(a+b+c)2:

In[1]:=
result = ResourceFunction[
  "SimplifyRepeatedSubexpressions"][(a + b + c)^3 + (a + b + c)^2]
Out[1]=

Reconstruct the original expression from the decomposed form:

In[2]:=
ReplaceAll @@ result
Out[2]=

Options

Finding many small common subexpressions may not be helpful:

In[3]:=
ResourceFunction["SimplifyRepeatedSubexpressions"][
 Solve[a x^2 + b x + c == 0, x]]
Out[3]=

Find only the largest with "MinLeafCount":

In[4]:=
ResourceFunction["SimplifyRepeatedSubexpressions"][
 Solve[a x^2 + b x + c == 0, x], "MinLeafCount" -> 10]
Out[4]=

Applications

Remove the discriminant from the quadratic solution equations:

In[5]:=
ResourceFunction["SimplifyRepeatedSubexpressions"][
 Solve[a x^2 + b x + c == 0, x], "MinLeafCount" -> 10]
Out[5]=

Properties and Relations

Reconstruct the original expression from the decomposed form by applying ReplaceAll:

In[6]:=
result = ResourceFunction[
  "SimplifyRepeatedSubexpressions"][(a + b + c)^3 + (a + b + c)^2]
Out[6]=
In[7]:=
ReplaceAll @@ result
Out[7]=

Possible Issues

The FullForm of subexpressions must match; in this case no match is found:

In[8]:=
ResourceFunction["SimplifyRepeatedSubexpressions"][
 a + b + c + (a + b + c)^2]
Out[8]=

This is because the outermost Plus has four arguments and not just the a, b and c:

In[9]:=
FullForm[a + b + c + (a + b + c)^2]
Out[9]=

If the input expression contains elements with HoldAll, HoldRest or HoldFirst, the contents will evaluate during the search:

In[10]:=
ResourceFunction["SimplifyRepeatedSubexpressions"][
 Hold[Print[{2 + 2, 2 + 2}]]]
Out[10]=

Neat Examples

Simplify the order three polynomial solution:

In[11]:=
ResourceFunction["SimplifyRepeatedSubexpressions"][
 Solve[a x^3 + b x^2 + c x + d == 0, x], "MinLeafCount" -> 30]
Out[11]=

And the order four polynomial solution:

In[12]:=
ResourceFunction["SimplifyRepeatedSubexpressions"][
 Solve[a x^4 + b x^3 + c x^2 + d x + e == 0, x], "MinLeafCount" -> 30]
Out[12]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

License Information