This is documentation for Mathematica 5, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)

Documentation / Mathematica / The Mathematica Book / Principles of Mathematica / Evaluation of Expressions /

2.6.10 Collecting Expressions During Evaluation

In 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.

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]


Here two intermediate results are also given.

In[2]:= Reap[Sow[a = 3]; a += Sow[a^2 + 1]; a = Sqrt[a + a^2]]


This computes a sum, collecting all terms that are even.

In[3]:= Reap[Sum[If[EvenQ[#], Sow[#], #]& [i^2 + 1], {i, 10}]]


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]]


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]


Here 1 is sown twice with tag x.

In[7]:= Reap[Sow[1, {x, x}]; Sow[2, y]; Sow[3, x], x]


Values sown with different tags always appear in different sublists.

In[8]:= Reap[Sow[1, {x, x}]; Sow[2, y]; Sow[3, x]]


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}]


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]


The tags can be part of the computation.

In[11]:= Reap[Do[Sow[i/j, GCD[i, j]], {i, 4}, {j, i}]]