This is a function using comprehensions
def combinations_of(_, 0), do: [[]]
def combinations_of([], _), do: []
def combinations_of([x | xt], n) do
for(y <- combinations_of(xt, n - 1), do: [x | y]) ++ combinations_of(xt, n)
end
but it eats a lot of memory (in a case of something like collection |> combinations_of(6)
).
Replacing it with
def combinations_of(_, 0), do: [[]]
def combinations_of([], _), do: []
def combinations_of([x | xt], n) do
Stream.map(combinations_of(xt, n - 1), fn y ->
[x | y]
end)
|> Stream.concat(combinations_of(xt, n))
end
doesn’t help and eats even more memory (obviously, because of recursion).
How to solve this problem?