4
$\begingroup$

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?

$\endgroup$
10
$\begingroup$

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

$\endgroup$
  • $\begingroup$ very helpful! Thanks for righting this. $\endgroup$ – user6546 Apr 3 '18 at 3:21
  • $\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
  • $\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 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. $\endgroup$ – J. M. will be back soon Apr 9 '18 at 3:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.