5
$\begingroup$

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}]?

$\endgroup$
4
  • $\begingroup$ Have a look at Sequence. $\endgroup$ Commented May 24, 2015 at 12:54
  • 4
    $\begingroup$ Look up @@@. $\phantom{}$ $\endgroup$ Commented May 24, 2015 at 12:57
  • $\begingroup$ Proposed duplicate: (24939) $\endgroup$
    – Mr.Wizard
    Commented May 24, 2015 at 13:29
  • $\begingroup$ if you like the /@ notation, you could use Apply[f] /@ args. $\endgroup$
    – SHuisman
    Commented Jan 12 at 18:03

4 Answers 4

7
$\begingroup$
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

$\endgroup$
5
$\begingroup$
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]}}

$\endgroup$
2
$\begingroup$

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]} *)
$\endgroup$
2
$\begingroup$

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]}*)
$\endgroup$

Your Answer

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

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