5
$\begingroup$

I would like to illustrate to users the use of Apply with an example.

Plus@@Range[5]
(*15*)

To display what is happening I'm interesting in showing the expression after the List head has been replaced by Plus, but before evaluation. I can do it abstractly with an arbitrary symbol:

f@@Range[5]
(*f[1, 2, 3, 4, 5]*)

How do I control the evaluation flow to do the same with f replaced by Plus?

Edit:

To be more precise, I was wondering if I could control the evaluation so that the output would be shown as:

 Plus[1,2,3,4,5]

With Range[5] being evaluated, but not Plus.

$\endgroup$
1
  • 2
    $\begingroup$ If you want to see the process, you can also do Trace@Apply[Plus, lis] // Column which gives screen shot !Mathematica graphics $\endgroup$
    – Nasser
    Nov 29 '21 at 10:44
9
$\begingroup$
expr = Range[5];
expr1 = Plus @@ expr;
expr2 = Defer@Plus @@ expr;
TreeForm /@ {expr, expr1, expr2}

enter image description here

$\endgroup$
7
$\begingroup$

Try this:

expr1 = Inactive[Plus] @@ Range[5]

The result is as follows:

enter image description here

If you need to further calculate it to the end make this:

expr2 = expr1 // Activate

(*  15  *)

Have fun!

$\endgroup$
1
  • $\begingroup$ This is close but not exactly what I had in mind. See edit. $\endgroup$
    – Whelp
    Nov 29 '21 at 12:24
5
$\begingroup$

Also

 HoldForm[Plus] @@ Range[5]
 (* Plus[1, 2, 3, 4, 5] *)

Comment: Use HoldForm or Defer (as in Syed's answer), depending on how the output is to be used. See the Properties and Relations section of the documentation for Defer.

$\endgroup$

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.