Collecting Expressions during Evaluation

In many computations you are concerned only with the final result of evaluating the expression given as input. But sometimes you also want 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]:=
Click for copyable input
Out[1]=
Here two intermediate results are also given.
In[2]:=
Click for copyable input
Out[2]=
This computes a sum, collecting all terms that are even.
In[3]:=
Click for copyable input
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]:=
Click for copyable input
This nests the function, reaping all cases below 1/2.
In[5]:=
Click for copyable input
Out[5]=
Sow[val,tag]sow val with a tag to indicate when to reap
Sow[val,{tag1,tag2,...}]sow val for each of the
Reap[expr,form]reap all values whose tags match form
Reap[expr,{form1,form2,...}]make separate lists for each of the
Reap[expr,{form1,...},f]apply f to each distinct tag and list of values

Sowing and reaping with tags.

This reaps only values sown with tag .
In[6]:=
Click for copyable input
Out[6]=
Here is sown twice with tag .
In[7]:=
Click for copyable input
Out[7]=
Values sown with different tags always appear in different sublists.
In[8]:=
Click for copyable input
Out[8]=
This makes a sublist for each form of tag being reaped.
In[9]:=
Click for copyable input
Out[9]=
This applies to each distinct tag and list of values.
In[10]:=
Click for copyable input
Out[10]=
The tags can be part of the computation.
In[11]:=
Click for copyable input
Out[11]=
New to Mathematica? Find your learning path »
Have a question? Ask support »