# Unexpected behavior with Map [closed]

Using Map, one can apply a function f to the elements of a list:

Clear[f];
Map[f,Range[10]]
(*{f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9], f[10]}*)


But the command does not seem to work if any modification is applied to f. For example:

Map[-f,Range[10]]
(*{(-f)[1], (-f)[2], (-f)[3], (-f)[4], (-f)[5], (-f)[6], (-f)[7], (-f)[8], (-f)[9], (-f)[10]}*)


This is illustrated with an example:

f[x_]=2x;
Map[f, Range[10]]
(*{2, 4, 6, 8, 10, 12, 14, 16, 18, 20}*)
Map[-f, Range[10]]
(*{(-f)[1], (-f)[2], (-f)[3], (-f)[4], (-f)[5], (-f)[6], (-f)[7], (-f)[
8], (-f)[9], (-f)[10]}*)


Is there a way to evaluate this expression to the desired result ?

• Take a look at FullForm@(-f) this is what you are mapping with while you should use Minus @* f or something. – Kuba May 30 '17 at 9:28
• You cannot do operations on the head in the way you desire. You cannot define -x = 4. Any reason you want it done this way ? The natural way would be to have Map[f, -Range[10]] instead of Map[-f, Range[10]] – Lotus May 30 '17 at 10:01
• @Lotus Yes, specifically, I was looking to map the sum of two functions f1 and f2 I have previously defined, as in Map[f1+f2, list]. Instead, I ham ressorting to applying them separately, Map[f1, list]+Map[f2,list], which is less compact. – Whelp May 30 '17 at 11:59
• Maybe Map[(f@# + g@#) &, Range[10]] where g[x_] = 3 x; (or, Range[10] // Map[(f@# + g@#) &, #] & – user1066 May 30 '17 at 12:17

As noted in comments, the standard ways to evaluate such result is to use Composition or pure function.

Using Composition:

Map[Minus@*f, Range[10]]


{-f[1], -f[2], -f[3], -f[4], -f[5], -f[6], -f[7], -f[8], -f[9], -f[10]}

Using pure function:

Map[(-f[#1])&, Range[10]]


{-f[1], -f[2], -f[3], -f[4], -f[5], -f[6], -f[7], -f[8], -f[9], -f[10]}

• or -Map[f, Range[10]] – user1066 May 30 '17 at 14:47

Heads in Mathematica can be any expression. Map is doing just as it is instructed.

Perhaps you would like an abstraction along these lines:

deepMap[template_, target_, lev_: {1}] :=
Map[
Replace[template &, s_Symbol :> s[#], {-1}, Heads -> False],
target,
lev
]


Now:

deepMap[-f, {1, 2, 3}]

deepMap[Sin + Cos, {a, b, c}]

deepMap[j^2/k - m, {{1, 2}, {3, 4}}, {2}]

{-f[1], -f[2], -f[3]}

{Cos[a] + Sin[a], Cos[b] + Sin[b], Cos[c] + Sin[c]}

{{j[1]^2/k[1] - m[1], j[2]^2/k[2] - m[2]}, {j[3]^2/k[3] - m[3], j[4]^2/k[4] - m[4]}}


In:

Clear[f]
f[s_][x_] := 2 x s
Map[f[1], Range[10]]
Map[f[-1], Range[10]]


Out:

{2, 4, 6, 8, 10, 12, 14, 16, 18, 20}

{-2, -4, -6, -8, -10, -12, -14, -16, -18, -20}