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}]?
Asked
Active
Viewed 2,061 times
5
H.v.M.
- 1,093
- 5
- 12
4 Answers
7
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
Bob Hanlon
- 157,611
- 7
- 77
- 198
5
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]}}
eldo
- 67,911
- 5
- 60
- 168
2
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]} *)
user1066
- 17,923
- 3
- 31
- 49
2
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]})
E. Chan-López
- 23,117
- 3
- 21
- 44
Sequence. – b.gates.you.know.what May 24 '15 at 12:54@@@. $\phantom{}$ – J. M.'s missing motivation May 24 '15 at 12:57/@notation, you could useApply[f] /@ args. – SHuisman Jan 12 '24 at 18:03