2
$\begingroup$

I'm trying to understand the Map and Apply notation and ran into a problem.

I define this function:

f23 = Function[x, x^2];
Map[f23, {1, 2, 4, 6, 5, 8}]

and correctly get

{1, 4, 16, 36, 25, 64}

or

f23[{1, 4, 16, 36, 25, 64}]

yields

{1, 4, 16, 36, 25, 64}

but if I use Apply

Apply[f23, {12, 2, 4, 6, 5, 8}]

I only get

144

the first element. If I try using @@ it behaves just as Apply as expected.

So if I understand why apply is only operating on the first element, I can perhaps continue to learn how to use @@

Update: f23@{12, 2, 4, 6, 5, 8}

gets me

{144, 4, 16, 36, 25, 64}

So it appears I don't understand the apply @@ function

$\endgroup$
  • 1
    $\begingroup$ It is not Apply, your function is defined to care about the first argument only. Confusing part is that x^2 threads over lists that is why f23[{..}] returns a list. You can Trace to check. $\endgroup$ – Kuba Jun 17 '17 at 6:26
  • 1
    $\begingroup$ Aside a simple mistake with argument you can find answers in: Scan vs. Map vs. Apply. Is it enough? $\endgroup$ – Kuba Jun 17 '17 at 6:28
  • $\begingroup$ @Kuba, I've got to read up on what a "head" is. Might make sense then, but thanks for the link $\endgroup$ – Tom Mozdzen Jun 17 '17 at 6:39
  • 1
    $\begingroup$ Take a look at documentation of Function, (Function[{u, v}, u^2 + v^4]), then SetDelayed, Listable etc. $\endgroup$ – Kuba Jun 17 '17 at 6:57
  • 1
    $\begingroup$ Here is another one: Can a function be made to accept a variable amount of inputs?. If those two linked topics are not exhausting the subject please try to rephrase the question, if they do I will link them as duplicates. $\endgroup$ – Kuba Jun 17 '17 at 6:59
4
$\begingroup$

Actually, your problem here is that you don't fully understand Function. The 2nd bullet point under Details in Function says

If there are more arguments supplied than [used by] the function, the remaining arguments are ignored. 

Let's trace the evaluation of Function[x, x^2] @@ {12, 2, 4}

Trace[Function[x, x^2] @@ {12, 2, 4}]

{Function[x, x^2] @@ {12, 2, 4}, Function[x, x^2][12, 2, 4], 12^2, 144}

We see that Apply changes the head List to Function[x, x^2] just as expected. Then Function gets the three arguments 12, 2, 4 and ignores all but the 1st as documented.

$\endgroup$
  • $\begingroup$ Ah - thank you. So when I do this: Function[x,x^2]@@{{12,2,4}}, I now get {144,4,16}. Not that the double brackets are useful, but confirms what one would expect. $\endgroup$ – Tom Mozdzen Jun 17 '17 at 21:06

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.