有没有办法获得List
List
并通过理解来运行它?或者下一个最好的东西是什么?
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]]
答案 0 :(得分:2)
您可以生成所有组合,然后为每个组合执行apply(f, combination)
:
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]))
输出:
[[1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [2, 3, 5], [2, 3, 6], [2, 4, 5],
[2, 4, 6]]
你可以通过不在combinations
中生成最终列表来加快速度,但需要一个函数并在那里应用它。