3

I'm having a problem concerning function addition. The following code shows an example that illustrates my problem. I had this list of functions that have the same variable. I had them by using the Total function and declared a function of that variable equal to the Total[list], like in this example:

f1[x_] := 2 x + 1;
f2[x_] := x;
f3[x_] = 4 x;
l1 = List[f1[x], f2[x], f3[x]];
o[x_] := Total[l1];
o[1]

The output of o[1] was 1+7x, instead of 8, which is what I want. Any suggestion on how to approach this problem? Thank you

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
RicardoP
  • 61
  • 1
  • 6

2 Answers2

4

Try this (as a side note, when defining functions using SetDelayed one doesn't have to include the semi-colon at the end of the line).

f1[x_] := 2 x + 1
f2[x_] := x
f3[x_] := 4 x

Use SetDelayed (i.e., :=) again to defrine l1

l1[x_] := List[f1[x], f2[x], f3[x]]

Inside the defintion for o use l1 with an argument

o[x_] := Total[l1[x]]

Then test

o[1]
(* 8 *)

o[2]
(* 15 *)

This is similar but not quite identical to what Nasser wrote in his comment.

Jack LaVigne
  • 14,462
  • 2
  • 25
  • 37
4

My new resource function ThroughOperator can do this:

f1[x_] := 2 x + 1;
f2[x_] := x;
f3[x_] := 4 x;
o = ResourceFunction["ThroughOperator"][f1 + f2 + f3];
o /@ Range[5]

{8, 15, 22, 29, 36}

If you have a list of functions or if somehow the expression f1 + f2 + f3 evaluates to something else inside of ResourceFunction["ThroughOperator"], you can also use:

list = {f1, f2, f3};
o = ResourceFunction["ThroughOperator"][list, Plus];
o /@ Range[5]
Sjoerd Smit
  • 23,370
  • 46
  • 75
  • Nice answer! What 's the advantage of this ResourceFunction compared to a list of pure functions {f1,f2,f3} and Total@Through[{f1, f2, f3}[5]]? – Ulrich Neumann Dec 23 '22 at 15:20
  • @UlrichNeumann Through[{f1, f2, f3}[5]] is annoying to map over lists, which is one of the main motivations I made ThroughOperator. Another reason is that Through[h[f1, f2][x]] sometimes suffers from order-of-evaluation issues that are difficult to circumvent. – Sjoerd Smit Jan 09 '23 at 10:47
  • Thank you for your explanation! – Ulrich Neumann Jan 09 '23 at 10:56