# How to declare that a function is arbitrary then specify them later? [duplicate]

I need to evaluate an expression, sum in this case, involving an arbitrary function. Below is a simplified version of what I wanted to do:

points = {1.3, 2.4};
f1[g_] = g^2 + 1;
f2[g_] = Sum[f1[g[points[[i]]]], {i, 2}];


I want to be general so g is an arbitrary function. It works for simple functions, for example, if I want g[x]=Sin[x], then

f2[Sin]


gives the correct answer 3.38469. My problem is, in the actual code, g is much more complicated. A simpler example will suffice. If I want g[x]=Sin[x]+Cos[x], then the following does not work:

f2[Sin +Cos]


Will be glad if someone can help or give a useful hint. Thank you in advance!

• You can use a pure function definition for g, using Function or &. For instance, try f2[Sin[#] + Cos[#]&]. Commented Dec 6, 2021 at 14:17
• Almost exactly the same question: mathematica.stackexchange.com/q/230934/7936 Commented Dec 6, 2021 at 15:44

First recommendation: use := to define your functions.

f1[g_] := g^2 + 1
f2[g_] := Sum[f1[g[points[[i]]]], {i, 2}]


This guarantees that g will be interpreted as the name of the argument pattern, rather than first evaluated as a global symbol.

Now, note that Sin+Cos isn't a function, it's just the sum of the symbols Sin and Cos, usually meaningless. Define a function:

h[x_] := Sin[x] + Cos[x]


Now, it's all fine:

f2[h]
(* 3.51934 *)


But now, a further recommendation: don't use Sum to add things. Sum is a tool of analysis, a way to figure out things like infinite sums. Better, and easier, to use Total:

f3[g_] := Total[f1[g /@ points]]
f3[h]
(* 3.51934 *)


Here, I map g to the points (/@), and take advantage of the fact that your f1 is implicitly Listable to further simplify. An advantage of Total here is that it just adds all your points, regardless of how many there are. You need not keep track. Another advantage, when you have many points, is that it's less subject to roundoff error than simply adding the points in order.

Clear["Global*"]

f1[x_] := x^2 + 1;


Using Composition ( @* ) and restricting the argument of f2 to expressions with the Head of Function and operating on a vector of variable length (length 2 in your example),

f2[g_Function] := Total[f1@*g /@ points]

Format[pt[n_]] := Subscript[pt, n]

n = 5;

points = Array[pt, n];

f2[g[#] &]


f2[Sin[#] &]


f2[Sin[#] + Cos[#] &] // Simplify
`

• Dear all, thank you so much! These are very helpful comments. As pointed out by evanb, this is a similar question to mathematica.stackexchange.com/questions/230934/… So this question might be deleted. Thank you! Commented Dec 8, 2021 at 1:42