5
$\begingroup$

In the documentation of Reap under "Applications" paragraph there is this example:

Reap[Sow[1, {b, b, c, a, c, a, b, d}], _, # &]

(* {1, {b, c, a, d}} *)

The second part of the output represents unsorted union of {b, b, c, a, c, a, b, d}.

I do not understand how this works. Neither Reap nor Sow represent any cycle or condition if I am not mistaken.

$\endgroup$
3
  • $\begingroup$ Ahhh... there is the cycle... I did not know that Sow[1, {b, b, c, a, c, a, b, d}] works like mapping over the second argument. Anyway, I have never used Reap - Sow in any code and I don't think I ever will. $\endgroup$ Nov 9, 2022 at 19:32
  • 4
    $\begingroup$ Reap/Sow can be useful to monitor steps or evaluations when numerically solving a problem with functions like NDSolve, FindRoot etc. For example EvaluationMonitor $\endgroup$ Nov 9, 2022 at 20:06
  • 1
    $\begingroup$ In addition, to list duplicates (using Reap/Sow): Reap[Sow[1,{b, b, c, a, c, a, b, d}],_,Pick[#1,Unitize[Length@#2-1],1]&][[2]] or to delete ALL duplicates (using Reap/Sow): Reap[Sow[1,{b, b, c, a, c, a, b, d}],_,Pick[#1,#2,{1}]&][[2]] $\endgroup$
    – user1066
    Nov 10, 2022 at 11:03

1 Answer 1

10
$\begingroup$

Note that

Sow[1, {b, b, c, a, c, a, b, d}]

is equivalent to

Sow[1,b]; Sow[1,b]; Sow[1,c]; Sow[1,a]; Sow[1,c]; Sow[1,a]; Sow[1,b]; Sow[1,d]

in the sense that they sow the same thing: They sow (the value 1) 3 times with tag b, 2 times with tag c, 2 times with tag a, 1 time with tag d. See the 3rd syntax of Sow in the documentation.

Therefore

Reap[Sow[1,{b,b,c,a,c,a,b,d}],_,f]
(* {1,{f[b,{1,1,1}],f[c,{1,1}],f[a,{1,1}],f[d,{1}]}} *)

consistent with the 4th syntax of Reap in the documentation.

In the example that OP considers, f = # &, which is the same as f = #1 &. For example, f[b,{1,1,1}] evaluates to b. This explains why

Reap[Sow[1,{b,b,c,a,c,a,b,d}],_,#&]
(* {1,{b,c,a,d}} *)
$\endgroup$

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