Map[f[#] + g[#] &, {a, b, c}] vs Map[f[x]+g[x]&, {a, b, c}]

My question is: why is the output different?

Map[f[#] + g[#] &, {a, b, c}]

(* {f[a] + g[a], f[b] + g[b], f[c] + g[c]} *)


Map[f[x] + g[x] &, {a, b, c}]

(* {f[x] + g[x], f[x] + g[x], f[x] + g[x]} *)
  • 7
    $\begingroup$ Take a look at the documentation to find out what is the role of the slot (#). $\endgroup$ – VLC Nov 15 '12 at 7:43
  • 2
    $\begingroup$ Maybe Map[ Function[x, f[x]+g[x]], {a,b,c} ] is more readable. Check out the documentation for Function. $\endgroup$ – Rolf Mertig Nov 15 '12 at 10:15
  • $\begingroup$ Maybe you want to ask the question: What are the values of # and of x ? $\endgroup$ – image_doctor Nov 15 '12 at 11:01
  • $\begingroup$ Perhaps you meant to compare something like the following? myfn[x_] := f[x] + g[x]; myfn /@ {a, b, c} == (f@# + g@# & /@ {a, b, c}) (=> True) $\endgroup$ – user1066 Nov 15 '12 at 11:31
  • $\begingroup$ To make the point perhaps more dramatically, what would you expect Map[f[5] + g[5] &, {a, b, c}] to give? Your second construction, with x instead of 5, is the same kind of situation. $\endgroup$ – murray Nov 15 '12 at 16:26

The Map function lets you apply a function to every element of a list. So:

Map[Sin, {0, Pi/2, Pi}]

applies Sin to each of the three values in the list which occupies the second place in the Map function call. The result is a list of numbers:

{0, 1, 0}

If you define your own functions, you can use them in a similar way:

double[x_] := x + x;

Map[double, {0, Pi/2, Pi}]

{0, π, 2 π}

You can use # or Slot, together with the ampersand (&), to refer to the arguments or parameters of a function, like this:

Map[Sin[#] + Cos[#] &, {0, Pi/2, Pi}]

{1, 1, -1}

When Mathematica doesn't understand what you typed, it returns it to you unchanged:

Map[f [x] g[x] &, {0, Pi/2, Pi}] 

{f[x] g[x], f[x] g[x], f[x] g[x]}

The syntax highlighter in the notebook should indicate which parts of your code don't mean anything to Mathematica. On my machine, it shows in blue:

screen grab

| improve this answer | |

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.