# Unexpected behavior with Map [closed]

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

Clear[f];
Map[f,Range]
(*{f, f, f, f, f, f, f, f, f, f}*)


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

Map[-f,Range]
(*{(-f), (-f), (-f), (-f), (-f), (-f), (-f), (-f), (-f), (-f)}*)


This is illustrated with an example:

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


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] instead of Map[-f, Range] – 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] where g[x_] = 3 x; (or, Range // 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]


{-f, -f, -f, -f, -f, -f, -f, -f, -f, -f}

Using pure function:

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


{-f, -f, -f, -f, -f, -f, -f, -f, -f, -f}

• or -Map[f, Range] – 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, -f, -f}

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

{{j^2/k - m, j^2/k - m}, {j^2/k - m, j^2/k - m}}


In:

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


Out:

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

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