# What makes Mathematica interpret Plus this way?

If I write:

Apply[Plus, Range[1, 10]]


Mathematica understands I want to sum all the numbers in the list and yields the total of the elements of the set. No suppose I do the following:

g[x_, y_] := x + y
Apply[g, Range[1, 10]]


Mathematica gives me as output:

g[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


Why does that happen?

• Because you define your g as a function that can have only two arguments, no more, no less. but Plus was implemented in a way to support variable number of arguments, in this case, 10 arguments. Read Functions with Variable Numbers of Arguments for more information. Aug 27 at 15:57

Apply simply changes the head of an expression, so that

Apply[newHead, oldHead[subexpr]]


becomes

newHead[subexpr]


Apply[g, Range[1, 10]]


becomes

Apply[g, List[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]


which in turn becomes

g[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


after the old head of List has been substituted by the new head g.

But your definition of g only specifies what should be done in the case that g receives two arguments. So Wolfram Language does not know how to evaluate the expression

g[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


and returns it as a symbolic expression.

EDIT

You could simply set

g = Plus;


to get the output you desire. Alternatively, you could define g as follows:

ClearAll[g];
g[s__] := Fold[Plus, {s}];


I don't see a good reason for doing this, so I am assuming that your question is purely of academic interest.

Look at the output of:

TreeForm[Range[1, 10]]


Apply[Plus, Range[1, 10]]


gives you 55 since, since the Head was List and it got replaced by Plus as this is what Apply does.

Next, you define a two argument function g:

g[x_, y_] := x + y;


and apply it:

Apply[g, Range[1, 10]]

g[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

TreeForm[%]


This time the head is replaced by g, but it can't do much since it needs two arguments at a time. Let's partition the range in twos.

t = Partition[Range[1, 10], 2]

{{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}}


Now apply:

Apply[g, t]

TreeForm[%]


That is not useful, let's try going one level deeper.

Apply[g, t, 1]

{3, 7, 11, 15, 19}


To see it before evaluation:

Apply[Defer[g], t, 1] // TreeForm


reveals that g is now acting at level 1.

You can see that function g is summing the two arguments being presented to it. I hope this helps you.