-1
$\begingroup$

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?

$\endgroup$
1
  • 6
    $\begingroup$ 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. $\endgroup$
    – Ben Izd
    Aug 27 at 15:57
9
$\begingroup$

Apply simply changes the head of an expression, so that

Apply[newHead, oldHead[subexpr]]

becomes

newHead[subexpr]

In particular, in your example,

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.

$\endgroup$
3
$\begingroup$

Look at the output of:

TreeForm[Range[1, 10]]

enter image description here

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[%]

enter image description here

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[%]

enter image description here

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.

enter image description here

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

$\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.