I'm trying to understand list comprehensions in Elixir.
The example I'm looking at is producing the permutations of a string from this answer.
def shuffle([], _), do: [[]]
def shuffle(_, 0), do: [[]]
def shuffle(list, i) do
for x <- list, y <- shuffle(list, i-1), do: [x|y]
end
How does this double-generator comprehension look when re-written without the comprehension? I made an attempt to implement the algorithm myself, but my implementation is appending to the list, rather than prepending as in the comprehension. I want to write the algorithm without the comprehension but with identical behaviour.
A comprehension without filters can be converted into a sequence of
Enum.flat_map
andEnum.map
. Specifically, all but the last one will becomeflat_map
and the last one will becomemap
. Here's a translation of your code:I tested with
A.shuffle([1, 2, 3, 4, 5], 2)
and the output looks identical to the original code in that question.Running Dogbert's example with the
flat_map
replaced withmap
really helped me see what was going on: