The Worker Ant
The Worker Ant

Reputation: 129

Comprehension with arbitrary number of arguments?

Is there a way to take a List of Lists and run it through a comprehension? Or what's the next best thing?

my_lists = [[1,2], [3,4], [5,6]]
# ... magic ...
do_a_for_with_these_lists &([&1,&2,&3])
# for a <- [1,2], b <- [3,4], c <- [5,6], do: [a,b,c]
[[1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6]]

Upvotes: 0

Views: 42

Answers (1)

Dogbert
Dogbert

Reputation: 222118

You can generate all combinations and then do apply(f, combination) for each:

defmodule A do
  def go(list, f), do: for c <- combinations(list, []), do: apply(f, c)

  def combinations([h | t], acc), do: for x <- h, c <- combinations(t, [x | acc]), do: c
  def combinations([], acc), do: [Enum.reverse(acc)]
end

IO.inspect A.go([[1, 2], [3, 4], [5, 6]], &([&1, &2, &3]))

Output:

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

You can speed this up by not generating the final list in combinations but taking a function and applying it right there.

Upvotes: 2

Related Questions