那么,我们来分析一下{A, B, C}这个例子。
首先,您想从中取出单个元素,然后获取其余部分。所以你需要编写一些函数来返回对列表:
pairs = [ (A, {B, C})
(B, {A, C})
(C, {A, B}) ]
对于这些对中的每一个,您都会得到一个单独的排列列表,可以从中得出,如下所示:
for pair in pairs do
head <- pair.fst // e.g. for the first pair it will be A
tails <- perms(pair.snd) // e.g. tails will be a list of permutations computed from {B, C}
您需要将head 附加到tails 的每个尾部,以获得完整的排列。所以完整的循环将是:
permutations <- []
for pair in pairs do
head <- pair.fst // e.g. for the first pair it will be A
tails <- perms(pair.snd) // e.g. tails will be a list of permutations computed from {B, C}
for tail in tails do
permutations.add(head :: tail); // here we create a complete permutation
head :: tail 表示我们将一个元素head 附加到列表tail 的开头。
现在,如何实现片段tails <- perm(pair.snd) 中使用的perms 函数。我们刚刚做到了!这就是递归的全部内容。 :)
我们仍然需要一个基本情况,所以:
perms({X}) = [ {X} ] // return a list of one possible permutation
所有其他情况的函数如下所示:
perms({X...}) =
permutations <- []
pairs <- createPairs({X...})
for pair in pairs do
head <- pair.fst // e.g. for the first pair it will be A
tails <- perms(pair.snd) // e.g. tails will be a list of permutations computed from {B, C}
for tail in tails do
permutations.add( head :: tail ); // here we create a complete permutation
return permutations