Function Repository Resource:

RecursiveRewrite

Source Notebook

Rewrite an expression, replacing repeatedly by strings

Contributed by: Enrique Zeleny

ResourceFunction["RecursiveRewrite"][expr]

rewrites expr, replacing repeatedly by strings.

Details and Options

Any string can be used in the "RewriteSymbol" option.

Examples

Basic Examples (4) 

Choose an expression:

In[1]:=
expr = (#1[[1, 2]] &) /@ Solve[8 x^4 + 42 x^3 + 64 x^2 + 71 x + 27 == 0, x, Quartics -> True];

Get a list of replacements to rewrite the expression:

In[2]:=
optexpr = ResourceFunction["RecursiveRewrite"][expr]
Out[2]=
In[3]:=
ReplaceRepeated @@ % // Short
Out[3]=

Recover the original expression, applying replacements only six times, starting with the final string:

In[4]:=
expr2 = Nest[# /. Last[optexpr] &, "c58", 6]
Out[4]=

To see the values of subexpressions, you can use the function FromRecursiveRewrite instead:

In[5]:=
ResourceFunction["FromRecursiveRewrite"][expr2[[1]], Last[optexpr], Tooltip[Framed[#1, Background -> GrayLevel[.95]], #2] &]
Out[5]=

Scope (1) 

RecursiveRewrite prevents evaluation as it rewrites:

In[6]:=
ResourceFunction["RecursiveRewrite"][
 Hold[{Quantity[x, "Dollars"], Print[1 + 1], Hold@Image[Plot[Sin[x], {x, 0, 2 \[Pi]}, ImageSize -> 200]]}]]
Out[6]=
In[7]:=
"c20" //. Last[%]
Out[7]=

Options (4) 

RewriteSymbol (4) 

Start with an expression:

In[8]:=
expr = (#1[[1, 2]] &) /@ Solve[8 x^4 + 42 x^3 + 64 x^2 + 71 x + 27 == 0, x, Quartics -> True];

Rewrite a subexpression using the symbol "R":

In[9]:=
optexpr2 = ResourceFunction["RecursiveRewrite"][expr[[1, 2]], "RewriteSymbol" -> "R"]
Out[9]=

Recover the subexpression:

In[10]:=
"R27" "R5" //. Last[%]
Out[10]=

Rewrite the expression inside the square root for only six steps and write the strings as subscripts:

In[11]:=
Nest[# /. Last[optexpr2] &, "R26", 6] /. s_String :> Subscript[R, StringDelete[s, "R"]]
Out[11]=

Possible Issues (1) 

Avoid using strings identical to rewrite symbols:

In[12]:=
ResourceFunction["RecursiveRewrite"][foo[x, "c3"]]
Out[12]=
In[13]:=
"c3" //. Last[%]
Out[13]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.1 – 19 October 2020
  • 1.0.0 – 06 March 2019

License Information