2.6.10 Collecting Expressions During EvaluationIn many computations one is concerned only with the final result of evaluating the expression given as input. But sometimes one also wants to collect expressions that were generated in the course of the evaluation. You can do this using Sow and Reap.
| Sow[val] | sow the value val for the nearest enclosing Reap | | Reap[expr] | evaluate expr, returning also a list of values sown by Sow |
Using Sow and Reap. | Here the output contains only the final result. | |
In[1]:=
a = 3; a += a^2 + 1; a = Sqrt[a + a^2]
|
Out[1]=
|
|
| Here two intermediate results are also given. | |
In[2]:=
Reap[Sow[a = 3]; a += Sow[a^2 + 1]; a = Sqrt[a + a^2]]
|
Out[2]=
|
|
| This computes a sum, collecting all terms that are even. | |
In[3]:=
Reap[Sum[If[EvenQ[#], Sow[#], #]& [i^2 + 1], {i, 10}]]
|
Out[3]=
|
|
Like Throw and Catch, Sow and Reap can be used anywhere in a computation. | This defines a function that can do a Sow. | |
In[4]:=
f[x_] := (If[x < 1/2, Sow[x]]; 3.5 x (1 - x))
|
|
| This nests the function, reaping all cases below 1/2. | |
In[5]:=
Reap[Nest[f, 0.8, 10]]
|
Out[5]=
|
|
| Sow[val, tag] | sow val with a tag to indicate when to reap | Sow[val, { , , ... }] | sow val for each of the | | Reap[expr, form] | reap all values whose tags match form | Reap[expr, { , , ... }] | make separate lists for each of the | Reap[expr, { , ... }, f] | apply f to each distinct tag and list of values |
Sowing and reaping with tags. | This reaps only values sown with tag x. | |
In[6]:=
Reap[Sow[1, x]; Sow[2, y]; Sow[3, x], x]
|
Out[6]=
|
|
| Here 1 is sown twice with tag x. | |
In[7]:=
Reap[Sow[1, {x, x}]; Sow[2, y]; Sow[3, x], x]
|
Out[7]=
|
|
| Values sown with different tags always appear in different sublists. | |
In[8]:=
Reap[Sow[1, {x, x}]; Sow[2, y]; Sow[3, x]]
|
Out[8]=
|
|
| The makes a sublist for each form of tag being reaped. | |
In[9]:=
Reap[Sow[1, {x, x}]; Sow[2, y]; Sow[3, x], {x, x, y}]
|
Out[9]=
|
|
| This applies f to each distinct tag and list of values. | |
In[10]:=
Reap[Sow[1, {x, x}]; Sow[2, y]; Sow[3, x], _, f]
|
Out[10]=
|
|
| The tags can be part of the computation. | |
In[11]:=
Reap[Do[Sow[i/j, GCD[i, j]], {i, 4}, {j, i}]]
|
Out[11]=
|
|
|