1
$\begingroup$

I've decided to post this question and self-answer, since this might be useful to others wishing to do the same thing.

I was wondering how to obtain non-null output from all parts of a compound expression. By default, only the result of the last part of a compound expression is output, for instance:

fun1[expr_] := (expr + x; expr + y; expr + z)
fun1[a]

a+z

fun1p := (# + x; # + y; # + z) &
fun1p[a]

a+z

One could use Print (or Echo)...

fun2[expr_] := (Print[expr + x]; Print[expr + y]; Print[expr + z])
out2 = fun2[a]

a+x

a+y

a+z

...but the output has Null content:

out2

(no output)

One gets the same result using Print with a pure function.

There are workarounds, but I sometimes find it syntactically convenient to obtain the outputs directly.

Note: This is not a duplicate of Compound Statements and returning earlier results in () parentheses , since there the OP was looking to Print the results (which displays the results, but has Null content), while I (as explained above) want to actually get the results (such that I could assign them to variables).

$\endgroup$
1
$\begingroup$

I received this answer, courtesy of Wolfram Technical Support. The desired result can be achieved using Sow and Reap:

 fun3[expr_] := 
 Reap[Sow[expr + x]; Sow[expr + y]; Sow[expr + z]][[2, 1]]
 out3 = fun3[a]

{a + x, a + y, a + z}

out3

{a + x, a + y, a + z}

fun3p := (Reap[Sow[# + x]; Sow[# + y]; Sow[# + z]])[[2, 1]] &
out3p = fun3p[a]

{a + x, a + y, a + z}

out3p

{a + x, a + y, a + z}

$\endgroup$
  • 2
    $\begingroup$ I'm curious as to what advantages this solution has over f[expr_]:={expr+x, expr+y, expr+z};. At first glance it seems that evaluation in a list is going to be in the same order as the terms (which only even matters if something is being set or redefined) so I'm not clear on what kind of use case this sort of construct would be ideal for. $\endgroup$ – eyorble Jan 8 at 2:27
  • $\begingroup$ @eyorble Good point. I was focused on achieving this with compound expressions, so I hadn't considered alternative approaches. I don't know if there are use cases in which a compound expression would work but your suggested construction would not. $\endgroup$ – theorist Jan 8 at 2:48

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.