3
$\begingroup$

In the following example, why do these two calls to Apply return different results?

list = {"a", "b"};
Apply[f, list]
Apply[f[#] &, list]

f[a, b]

f[a]

In contrast, when using Map (which is a different function from Apply), these two calls return results identical to each other:

list = {"a", "b"};
Map[f, list]
Map[f[#] &, list]

{f["a"], f["b"]}

{f["a"], f["b"]}

$\endgroup$
2
  • 3
    $\begingroup$ Keep in mind # is short for Slot[1], which represents (only) the first argument. Also remember Trace or TracePrint: On simple code, such as Apply[f, list] // Trace and Apply[f[#] &, list] // Trace, the Trace gives a nice sequence that shows how an expression is evaluated. (TracePrint shows more and is therefore both more complete and more complicated to follow.) $\endgroup$
    – Michael E2
    Aug 7, 2021 at 18:30
  • 2
    $\begingroup$ Another difference, not exhibited in this question, is that if f has Attributes, then f[##] & does not. In practice, this matters most when f has a Hold* attribute such as HoldAll. [A better question might be what are the differences between f and f[#] &.] $\endgroup$
    – Michael E2
    Aug 7, 2021 at 18:41

1 Answer 1

6
$\begingroup$

Oh, I was also surprised by the differenxe, but I have an explanation for it: By using f[#]&, you explicitly say that the functions shall only use the first argument. Use ## otherwise.

Apply[f[#] &, list]
Apply[f[##] &, list]

f["a"]

f["a", "b"]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.