3
$\begingroup$

I have a list of functions list, with 1-5 elements, each of which is one of the following functions:

{f1, f2, f3, f4, f5}

I also have 2 variables a, b. I would like to apply the functions in list to these variables, however there is one caveat which is holding me back. f1, f2, and f3 take no arguments. f4 takes a as an argument, and f5 takes a and b as arguments. I just want to execute all the functions in the list, not store the output in a list or anything, just execute them.

I know how to apply a list of functions to an argument but the fact that some of them take arguments and some don't has stumped me. How can I get this to work?

$\endgroup$
3
  • 1
    $\begingroup$ So your functions are sth like f3:=1, f4[x_]:=x and f5[x_, y_]:=x+y? $\endgroup$
    – corey979
    Jan 1, 2017 at 17:32
  • $\begingroup$ @corey979 That is correct, however, they have print functions, and don't actually return anything, so I don't want to store the output. $\endgroup$
    – Nico A
    Jan 1, 2017 at 17:40
  • $\begingroup$ Usually we ask for a minimum working example to avoid misunderstandings. I suspect there's a better way to do what you need that doesn't involve executing the functions as written... $\endgroup$
    – Jens
    Jan 1, 2017 at 17:44

1 Answer 1

3
$\begingroup$

Maybe something like this:

ClearAll[tF, f1, f2, f3, f4, f5]
tF = Function[{x, y}, 
      Switch[Head /@ {#[x, y], #@x}, {#, #}, #[], {#, _}, #[x], _, #[x, y]]] &;

Example:

f1[] := 1; f2[] := 2; f3[] := 3; f4[x_] := x; f5[x_, y_] := x + y; 
flist = {f1, f2, f3, f4, f5};

Through[(tF /@ flist)[x, y]]
(* or *) Operate[tF, #[x, y]] & /@ flist

{1, 2, 3, x, x + y}

Or, use tF to define an operator:

ClearAll[thruF]
thruF[funcs_] := Through[(tF /@ funcs)@##] &;

thruF[{f1, f2, f3, f4, f5}][x, y]

{1, 2, 3, x, x + y}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.