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}]}
-
-
$\begingroup$ @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. $\endgroup$ – Teg Louis Apr 5 '18 at 20:56
-
3$\begingroup$ @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 tagtag
with it, whileReap[expr, tag]
is there to watch for and catch anything produced with the tagtag
by anySow[]
inside, all while evaluatingexpr
. $\endgroup$ – J. M.'s ennui♦ Apr 9 '18 at 3:28