# Better definitions of Reap and Sow

I am having tremendous difficulty understanding Reap and Sow in Mathematica. The definitions are pretty circular. When I look at the definition of Sow, I get, "specifies that e should be collected by the nearest enclosing Reap,specifies that e should be collected by the nearest enclosing Reap whose pattern matches tag, and specifies that e should be collected once for each pattern that matches a tag". Then for reap, they do the same thing by using Sow in two of the definitions. I don't fully understand either. And the examples use tags in a way I don't really think of as tags in common English or real analysis. So, what are they actually talking about?

Here a quick example how Reap and Sow are typically used:

Reap[
Do[
If[OddQ[i], Sow[i, "Odd"], Sow[i, "Even"]],
{i, 1, 20}],
_, Rule
][[2]]


{"Odd" -> {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}, "Even" -> {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}}

Here _ in Reap means that arbitrary tags should be collected by this particular Reap.

Other patterns than _ are useful when we are dealing with nested instances of Reap. In the following, the inner Reap collects only tags of the form "Odd" while the outer collects "Even":

b = Reap[
a = Reap[
Do[
If[OddQ[i], Sow[i, "Odd"], Sow[i, "Even"]],
{i, 1, 20}],
"Odd", Rule
][[2]],
"Even", Rule
][[2]];
a
b


{"Odd" -> {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}}

{"Even" -> {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}}

Replacing Rule with any other function, say f leads to

Reap[
Do[
If[OddQ[i], Sow[i, "Odd"], Sow[i, "Even"]],
{i, 1, 20}],
_, f
][[2]]


{f["Odd", {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}], f["Even", {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}]}

• very helpful! Thanks for righting this. Apr 3, 2018 at 3:21
• @Henrik I am wondering if there is a more mathematical definition than what is given by Mathematica or through examples, like something using formal logic.
– user54649
Apr 5, 2018 at 20:56
• @Teg, I'm not sure why you need a "mathematical definition" here; Sow[arg, tag] is basically an instruction to "set aside" arg, and associate the tag tag with it, while Reap[expr, tag] is there to watch for and catch anything produced with the tag tag by any Sow[] inside, all while evaluating expr. Apr 9, 2018 at 3:28