How to construct the function combinationsF ?

list1 = {x, y}
list2 = {{a, b}, {c, d}, {e, f}}
combinationsF[list1, list2]
(*should give {F[x,a] F[y,b],F[x,c] F[y,d],F[x,e] F[y,f]}*)

I've tried Thread, MapThread, Apply and combinations but I'm missing something

  • $\begingroup$ {list1, list2} // (Tuples /* Map[MapThread[F]] /* Catenate) $\endgroup$ Feb 8 at 17:35

4 Answers 4

Inner[F, list1, #, Sequence] & /@ list2

{F[x, a], F[y, b], F[x, c], F[y, d], F[x, e], F[y, f]}

Compare with the following that can be flattened later, if required.

Inner[F, list1, #, List] & /@ list2

{{F[x, a], F[y, b]}, {F[x, c], F[y, d]}, {F[x, e], F[y, f]}}

  • 4
    $\begingroup$ (+1) For 12.1+ we can make it even easier: Inner[ReverseApplied[F], list2, list1, Sequence] $\endgroup$
    – Ben Izd
    Feb 8 at 18:00
  • 1
    $\begingroup$ Thank you! You've got a very elegant and short answer. Specially with the variation of Ben Izd. About answers with Threaded, I didn't download v13.1 yet (sorry!) $\endgroup$
    – Albercoc
    Feb 8 at 23:10
  • 3
    $\begingroup$ Not as neat as the Ben Izd variation, but Inner[F[#2,#1]&, list2, list1,Sequence] maybe also deserves a mention? $\endgroup$
    – user1066
    Feb 9 at 7:38

This can be achieved with the new function Threaded (introduced in V13.1):

SetAttributes[f1, Listable]
f1[Threaded[list1], list2]

{{f[x, a], f[y, b]}, {f[x, c], f[y, d]}, {f[x, e], f[y, f]}}

{f[x, a], f[y, b], f[x, c], f[y, d], f[x, e], f[y, f]}

If you don't want to mess with the attributes of the function itself you can use Function:

Flatten[Function[{x, y}, f2[x, y], Listable][Threaded[list1], list2]]

{f2[x, a], f2[y, b], f2[x, c], f2[y, d], f2[x, e], f2[y, f]}

  Sequence @@ MapThread[F,{list1, j}],
  {j, list2}

{F[x, a], F[y, b], F[x, c], F[y, d], F[x, e], F[y, f]}


Another way to do this using Table:

F @@@ (Join @@ Table[Transpose@{list1, list2[[i]]}, {i, 1, Length[list2]}])

(*{F[x, a], F[y, b], F[x, c], F[y, d], F[x, e], F[y, f]}*)

Your Answer

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

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