Wolfram Research

Function Repository Resource:

ThroughOperator (1.0.0) current version: 1.0.1 »

Source Notebook

An operator that applies multiple functions to one set of arguments

Contributed by: Sjoerd Smit

ResourceFunction["ThroughOperator"][{f1,f2,}][arg1,arg2,]

returns {f1[arg1,arg2,],f2[arg1,arg2,],}.

ResourceFunction["ThroughOperator"][{f1,f2,}, h][args,]

returns h[f1[args,],f2[args,],].

ResourceFunction["ThroughOperator"][<|key1f1,key2f2,|>, h][args,]

returns <|key1f1[args,],key2f2[args,],|>.

Details

ResourceFunction["ThroughOperator"] is an alternative to Through that's easy to use as an operator and also works with an Association of functions.
ResourceFunction["ThroughOperator"] works with heads other than List in the first argument.

Examples

Basic Examples (2) 

Apply a list of functions to some arguments:

In[1]:=
ResourceFunction["ThroughOperator"][{Sin, Cos, Tan}][N[Pi/3]]
Out[1]=

ThroughOperator can be mapped easily:

In[2]:=
ResourceFunction["ThroughOperator"][{Sin, Cos, Tan}] /@ {1, 2, 3}
Out[2]=
In[3]:=
ResourceFunction["ThroughOperator", ResourceVersion->"1.0.0"][{f, g}] @@@ {{1, 2}, {3, 4}, {5, 6}}
Out[3]=

Scope (4) 

ThroughOperator works with other heads as well:

In[4]:=
ResourceFunction["ThroughOperator"][h[f, g]] /@ Range[3]
Out[4]=

Define an operator that generates an Association with function values:

In[5]:=
ResourceFunction["ThroughOperator"][<|"Sin" -> Sin, "Cos" -> Cos|>] /@
  Range[3]
Out[5]=

Compute a number of booleans for a number use And to test if they are all True:

In[6]:=
ResourceFunction["ThroughOperator"][
  And[IntegerQ, OddQ, PrimeQ]] /@ {0.5, 2, 3, 4}
Out[6]=

This can be achieved with the 2-argument form as well:

In[7]:=
ResourceFunction["ThroughOperator"][{IntegerQ, OddQ, PrimeQ}, And] /@ {0.5, 2, 3, 4}
Out[7]=

Note that only the necessary functions are evaluated:

In[8]:=
ResourceFunction["ThroughOperator", ResourceVersion->"1.0.0"][{Echo@*IntegerQ, Echo@*OddQ, Echo@*PrimeQ}, And][0.5]
Out[8]=
In[9]:=
ResourceFunction["ThroughOperator", ResourceVersion->"1.0.0"][{Echo@*IntegerQ, Echo@*OddQ, Echo@*PrimeQ}, Or][0.5]
Out[9]=

The 2-argument form of ThroughOperator is convenient for functions that would evaluate prematurely in the 1-argument form:

In[10]:=
myFragilefun[i__Integer] := Plus[i];
myFragilefun[__] := $Failed;
ResourceFunction["ThroughOperator"][myFragilefun[# &, #^2 &]][3]
Out[12]=
In[13]:=
ResourceFunction["ThroughOperator"][{# &, #^2 &}, myFragilefun][3]
Out[13]=

Other functions will work correctly in the 1-argument form but issue messages:

In[14]:=
ResourceFunction["ThroughOperator"][
  StringJoin[ToString, " = " &, TextString]][Today]
Out[14]=

These messages can be avoided with the 2-argument form:

In[15]:=
ResourceFunction["ThroughOperator"][{ToString, " = " &, TextString}, StringJoin][Today]
Out[15]=

Publisher

Sjoerd Smit

Version History

  • 1.0.1 – 19 December 2022
  • 1.0.0 – 13 December 2022

Related Resources

License Information