4
$\begingroup$

I have been believing in Wolfram language that several forms of application of a function are equivalent:

f[a]
f@a
a//f
a~f~b (*for more than one argument*)

But why the last two rows of codes do not work below?

x := Sum[Sow[i^2, (-1)^i], {i, 10}]

Reap[x]
Reap@x
x // Reap
x~Reap~_
x~Reap~{-1, 1}
Reap[#, {-1, 1}] &@x
x // Reap[#, {-1, 1}] &

which give

{385, {{1, 9, 25, 49, 81}, {4, 16, 36, 64, 100}}}
{385, {{1, 9, 25, 49, 81}, {4, 16, 36, 64, 100}}}
{385, {{1, 9, 25, 49, 81}, {4, 16, 36, 64, 100}}}
{385, {{1, 9, 25, 49, 81}, {4, 16, 36, 64, 100}}}
{385, {{{1, 9, 25, 49, 81}}, {{4, 16, 36, 64, 100}}}}
{385, {{}, {}}}
{385, {{}, {}}}

Are there some peculiarities when Reap meets Function?

$\endgroup$
4
  • 2
    $\begingroup$ try Reap[#, {-1, 1}] &@Unevaluated[x] and Unevaluated[x] // Reap[#, {-1, 1}] & $\endgroup$
    – kglr
    Jul 25, 2018 at 7:03
  • $\begingroup$ @kglr It works, thanks! $\endgroup$ Jul 25, 2018 at 7:04
  • 1
    $\begingroup$ @Mr.Wizard, maybe Function that returns the second argument of Reap? $\endgroup$
    – kglr
    Jul 25, 2018 at 8:02
  • $\begingroup$ @kglr Better than I had remembered existing. $\endgroup$
    – Mr.Wizard
    Jul 25, 2018 at 8:36

2 Answers 2

4
$\begingroup$

This is the result of the different attributes between Reap and a (default) Function. Observe that Reap has HoldFirst:

Attributes[Reap]
{HoldFirst, Protected}

Without this the Sow expression is evaluated before Reap ever has a chance to see it. Adding HoldFirst to your Function will fix this:

Function[, Reap[#, {-1, 1}], HoldFirst] @ x
x // Function[x, Reap[x, {-1, 1}], HoldFirst]
{385, {{{1, 9, 25, 49, 81}}, {{4, 16, 36, 64, 100}}}}

{385, {{{1, 9, 25, 49, 81}}, {{4, 16, 36, 64, 100}}}}

Note that the first line uses an undocumented but longstanding syntax. This syntax is especially useful when you want to use SlotSequence in a Function with attributes. See:

$\endgroup$
3
$\begingroup$

An alternative is to use Unevaluated[x] to prevent evaluation of x before it is passed to Reap[#, {-1, 1}]:

Reap[#, {-1, 1}] &@Unevaluated[x]
Unevaluated[x] // Reap[#, {-1, 1}] &

both give

{385, {{1, 9, 25, 49, 81}, {4, 16, 36, 64, 100}}}

$\endgroup$

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