Sometimes because of conditionals, you cannot guarantee that Sow
will be called at least once.
Reap[Sow[1]][[2,1]]
results in {1}
, which is perfect if one was going to discard the end value anyway, because only the list of sown values has value.
Reap[Null][[2, 1]]
raises exception
"Part::partw: Part 1 of {} does not exist."
I use this code
ClearAll[reapList]
reapList::usage="gracefully collect all Sow expressions into list";
SetAttributes[reapList,HoldAll]
reapList[r__]:=Flatten[Reap[r,{_}][[2]],2]
(* unit tests follow *)
reapList[Sow[15]]
{15}
reapList[Sow[{}]]
{{}}
reapList[Sow[{16,17}];Sow[18];Print["hello"];Sow[{19,20}];21]
hello
{{16,17},18,{19,20}}
reapList[Null]
{}
reapList[Sow[Null]; Sow[{Null}]]
{Null,{Null}}
reapList[For[i = 95, i <= 100, i++, If[PrimeQ[i*2 - 1], Sow[i]]]]
{96, 97, 99, 100}
reapList[For[i = 101, i <= 105, i++, If[PrimeQ[i*2 - 1], Sow[i]]]]
{}
but there might be a better way than use of pattern {_}
and Flatten[ ... ,2]
that is so much shorter not much value in creating helper function.
Also, not clear to me how to generalize the "reapList" helper function for use with tags.
Sow[Null]
andSow[{Null}]
should do $\endgroup$Flatten[Reap[r][[2]], 1]
works $\endgroup$