Elixir:没有语法糖的情况下,多生成器列表理解是什么样的? [英] Elixir: What does a multiple-generator list comprehension look like without the syntax sugar?
问题描述
我试图了解Elixir中的列表理解.
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.
推荐答案
不带过滤器的理解可以转换为Enum.flat_map
和Enum.map
的序列.具体来说,除了最后一个以外的所有都将变为flat_map
,最后一个将变为map
.这是您的代码的翻译:
A comprehension without filters can be converted into a sequence of Enum.flat_map
and Enum.map
. Specifically, all but the last one will become flat_map
and the last one will become map
. Here's a translation of your code:
list
|> Enum.flat_map(fn x ->
shuffle(list, i - 1)
|> Enum.map(fn y ->
[x | y]
end)
end)
我用A.shuffle([1, 2, 3, 4, 5], 2)
进行了测试,输出看起来与该问题中的原始代码相同.
I tested with A.shuffle([1, 2, 3, 4, 5], 2)
and the output looks identical to the original code in that question.
这篇关于Elixir:没有语法糖的情况下,多生成器列表理解是什么样的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!