9
$\begingroup$

I would like to apply a function to a list of lists, while using each of the 2 elements of the list in a SlotSequence in two different places in the function.

What I am working with is

MyFunction[##[[1]]][##[[2]]] &@{{1, 2, 3}, {4, 5, 6}}

which outputs

MyFunction[{1, 2, 3}][{4, 5, 6}]

However instead I would like the output without the { and }

MyFunction[1, 2, 3][4, 5, 6]

This needs to hold for arbitrary lists of equal length {1,2,3} and {4,5,6}. Any advice is appreciated!

$\endgroup$
2
  • $\begingroup$ Maybe (MyFunction @@ #1) @@ #2 & @@ {{1, 2, 3}, {4, 5, 6}}? $\endgroup$
    – Michael E2
    Apr 28 '18 at 21:46
  • $\begingroup$ Perfect! I had a hunch that it should have been done in two steps in a sense, but I had no idea how that might be done. Thanks! $\endgroup$
    – user47636
    Apr 28 '18 at 21:47
9
$\begingroup$

User Michel E2 has already given a good answer. An alternative is to use (hat tip to Kuba for their suggestion):

Fold[Apply, MyFunction, {{1, 2, 3}, {4, 5, 6}}]

which evaluates to the same expression.

I'm not sure what exactly your goal is, but note that the code above works for lists of arbitrary length:

Fold[Apply, MyFunction, {{1, 2, 3}, {4, 5, 6}, {7, 8}, {9}}]
(* MyFunction[1, 2, 3][4, 5, 6][7, 8][9] *)

For fun: in the case of two lists, you can also use pattern replacements:

{{1, 2, 3}, {4, 5, 6}} /. {{a__}, {b__}} -> MyFunction[a][b]

which yields, once again, the same output.

$\endgroup$
1
  • 2
    $\begingroup$ Thanks for your response, I think I actually like the fact that using Fold works for lists of arbitrary length because I might need to use that later in what I am doing. $\endgroup$
    – user47636
    Apr 29 '18 at 22:43
9
$\begingroup$

This gets the desired result:

(MyFunction @@ #1) @@ #2 & @@ {{1, 2, 3}, {4, 5, 6}}
(*  MyFunction[1, 2, 3][4, 5, 6]  *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy