Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.
  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]} *)

and

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

(* {f[x] + g[x], f[x] + g[x], f[x] + g[x]} *)
share|improve this question
7  
Take a look at the documentation to find out what is the role of the slot (#). –  VLC Nov 15 '12 at 7:43
2  
Maybe Map[ Function[x, f[x]+g[x]], {a,b,c} ] is more readable. Check out the documentation for Function. –  Rolf Mertig Nov 15 '12 at 10:15
    
Maybe you want to ask the question: What are the values of # and of x ? –  image_doctor Nov 15 '12 at 11:01
    
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) –  TomD Nov 15 '12 at 11:31
    
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. –  murray Nov 15 '12 at 16:26
add comment

1 Answer

up vote 5 down vote accepted

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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