2

According to the Mathematica guide,

In[26]:= f /@ g[x, y, z]

Out[26]= g[f[x], f[y], f[z]]

In a simple example, this works as desired with symbolic values:

In[139]:= f[a_] := a^2; g[x_, y_, z_] := x + y + z ; 
          f /@ g[x, y, z]

Out[140]= x^2 + y^2 + z^2

However this does not work with integer entries:

In[141]:= f /@ g[1, 2, 3]

Out[141]= 6

Why does f /@ g[1, 2, 3] return 6 instead of 14?

Minkowski
  • 143
  • 3
  • To see what is going on you may use "Trace": f /@ g[1, 2, 3] // Trace and you then note that g is evaluated before f – Daniel Huber Oct 23 '20 at 10:50
  • @DanielHuber I see, but why is f evaluated before g when it is applied to symbolic values x,y,z? I don't get why the evaluation is different. – Minkowski Oct 23 '20 at 11:29
  • Actually f /@ (x + y) returns x^2 + y^2; but f /@ (2+3) returns 5 ! That is, f is not even evaluated... . – Minkowski Oct 23 '20 at 11:37
  • f /@ g similar to Pullback in mathematics :-) Plus[2+3] and Plus[x+y] are difference since Plus[x+y] need to defer calculate, I think. – cvgmt Oct 23 '20 at 12:06
  • 1
    @Minkowski g[1,2,3] it is not a function, it is numerical expression. Try, for instance f /@ g[x, y, 3] – Alex Trounev Oct 23 '20 at 12:35
  • Okay, I see what is the reason. So what would the correct sintaxis be if I want to get g[f[1], f[2]],f[3]] = 1^2 + 2^2 + 3^3 = 14 ? – Minkowski Oct 23 '20 at 13:32
  • 2
    One way f /@ Unevaluated[g[1, 2, 3]] – Rohit Namjoshi Oct 23 '20 at 13:49
  • 3
    Compare: f /@ g[x, y, z] // Trace and f /@ g[1, 2, 3] // Trace. You see that in both cases g gets evaluated (MMA evaluates arguments before functions). However the expression Plus[x,y,z] can not be evaluated further, but Plus[1,2,3] can. In the former case f maps onto Plus[x,y,z], in the latter onto 6 what is an atom. – Daniel Huber Oct 23 '20 at 13:53

2 Answers2

2

The correct input for the intention is:

f /@ Unevaluated[g[Unevaluated[1], Unevaluated@2, Unevaluated@3]]

(* 14 *)

for numbers according to Unevaluated

Steffen Jaeschke
  • 4,088
  • 7
  • 20
  • Or (f /@ Inactive[g][1, 2, 3]) // Activate – Bob Hanlon Oct 23 '20 at 18:28
  • Okay, but is there a more intuitive explanation of what went wrong here? For those of us that don't want to guess random combinations of evaluate or unevaluate when our code doesn't work. – Steven Sagona Oct 23 '20 at 23:18
2

Given the explanation of the problem in the comments above, explicitly mapping f on the list is likely the cleanest approach in this case.

g @@ f /@ {1,2,3}
Jean-Pierre
  • 5,187
  • 8
  • 15