简体   繁体   English

Erlang中的排列示例

[英]Permutations example in Erlang

I have a question about an Erlang Perms implementation: 我有一个关于Erlang Perms实现的问题:

 perms([]) -> [[]];
 perms(L) -> [[H|T] || H <- L, T <- perms(L--[H])].

The code above is from a book named Erlang Programming , it looks very simple but run perfectly. 上面的代码来自一本名为Erlang Programming的书,它看起来非常简单但运行完美。 What I'm confusing about is how it works. 我困惑的是它是如何工作的。 For example, let's run it with a parameter like perms("12") , then if we analyze the process of recursion. 例如,让我们使用perms("12")类的参数运行它,然后如果我们分析递归过程。 I think that the first return's result will be like [[1|perms[2]->[[2]|[[]]]] and this equals [[1|[[2]|[[]]]] . 我认为第一个返回的结果将类似于[[1|perms[2]->[[2]|[[]]]] ,这等于[[1|[[2]|[[]]]] But it is a wrong expression in Erlang shell. 但它在Erlang shell中是一个错误的表达。

The general behavior of list comprehension is to generate the cross product of all generators (after applying the defined filters). 列表推导的一般行为是生成所有生成器的叉积(在应用定义的过滤器之后)。 It is better illustrated by an example: 通过一个例子更好地说明:

1> [{X,Y} || X <- [1,2,3], Y <- [a,b,c]].
[{1,a},{1,b},{1,c},{2,a},{2,b},{2,c},{3,a},{3,b},{3,c}]
2> 

in the permutation code example, the list comprehension is executed this way: 在排列代码示例中,列表推导以这种方式执行:

H <- L is a generator, it will generate one value for each term of the input list L. in your case, L = "12", it will generate 2 terms the characters $1 and $2 , and it will build the cross product with the result of the second generator: T <- perms(L--[H]) H <- L是一个生成器,它将为输入列表L的每个项生成一个值。在您的情况下,L =“12”,它将生成2个术语,字符$1$2 ,它将构建交叉积与第二个发电机的结果: T <- perms(L--[H])

Here there is something very smart, the second generator depends on the first one, each element of the first generator will be combined with its own list from the second generator. 这里有一些非常聪明的东西,第二个发电机依赖于第一个发电机,第一个发电机的每个元件将与第二个发电机的自己的列表相结合。 So $1 will be combine with the generated terms from perms(L--[$1]) = perms("2") 因此$1将与perms(L--[$1]) = perms("2")生成的术语组合

If you try to evaluate perms("2") , the same analysis shows that the first generator generates one single term $2 to combine with perms([]) 如果你试图评估perms("2") ,同样的分析表明第一个生成器生成一个单词$2perms([])

the last term evaluate to [[]] and will generate an empty list. 最后一个术语评估为[[]]并将生成一个空列表。

we can build now the intermediate result: [[H|T]] = [[$2|[]]] = [[$2]] . 我们现在可以建立中间结果: [[H|T]] = [[$2|[]]] = [[$2]]

This result will generate the single term [$2] . 该结果将生成单个术语[$2] So the top level result will be (taking into account all generated terms) [[$1|[$2]],[$2|[$1]] = [[$1,$2],[$2,$1]] = ["12","21"] . 因此,最高级别的结果将是(考虑所有生成的条款) [[$1|[$2]],[$2|[$1]] = [[$1,$2],[$2,$1]] = ["12","21"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM