I have a function f[m,n]
and a list of arguments args = {{m1,n1},{m2,n2},{m3,n3},{m4,n4}, ...}
that I want to apply to it. I tried f/@args
, but this yields {f[{m1,n1}], ...}
. Is there a more elegant solution than defining the function as f[{m,n}]
?
4 Answers
args = {{m1, n1}, {m2, n2}, {m3, n3}, {m4, n4}};
f @@@ args
{f[m1, n1], f[m2, n2], f[m3, n3], f[m4, n4]}
Apply[f, args, {1}]
{f[m1, n1], f[m2, n2], f[m3, n3], f[m4, n4]}
f @@ # & /@ args
{f[m1, n1], f[m2, n2], f[m3, n3], f[m4, n4]}
f[Sequence @@ #] & /@ args
{f[m1, n1], f[m2, n2], f[m3, n3], f[m4, n4]}
% == %% == %%% == %%%%
True
args = {{m1, n1}, {m2, n2}, {m3, n3}, {m4, n4}};
Since V 13.1 we could also MapApply
MapApply[f] @ args
{f[m1, n1], f[m2, n2], f[m3, n3], f[m4, n4]}
And since V 14.0 ComapApply
to apply more than one function
ComapApply[{f, g}] /@ args
{{f[m1, n1], g[m1, n1]}, {f[m2, n2], g[m2, n2]}, {f[m3, n3], g[m3, n3]}, {f[m4, n4], g[m4, n4]}}
For versions prior to 14.0:
Query[All, Apply /@ {f, g}] @ args
{{f[m1, n1], g[m1, n1]}, {f[m2, n2], g[m2, n2]}, {f[m3, n3], g[m3, n3]}, {f[m4, n4], g[m4, n4]}}
In addition:
args = {{m1, n1}, {m2, n2}, {m3, n3}, {m4, n4}};
MapThread[f, Transpose@args]
(* {f[m1,n1],f[m2,n2],f[m3,n3],f[m4,n4]} *)
An alternative is to use BlockMap
:
args = {{m1, n1}, {m2, n2}, {m3, n3}, {m4, n4}};
BlockMap[Sequence @@ f @@@ # &, args, 2]
(*{f[m1, n1], f[m2, n2], f[m3, n3], f[m4, n4]}*)
Sequence
. $\endgroup$@@@
. $\phantom{}$ $\endgroup$/@
notation, you could useApply[f] /@ args
. $\endgroup$