[英]How does this Haskell function to calculate permutations using list comprehension work?
I'm reading Simon Thompson's Haskell: The Craft of Functional Programming , and I'm wondering how does this work: 我正在阅读Simon Thompson的Haskell:函数式编程工艺,我想知道它是如何工作的:
perms [] = [[]]
perms xs = [ x:ps | x <- xs , ps <- perms ( xs\\[x] ) ]
I can't seem to grasp how that perms( xs\\\\[x] )
is supposed to function. 我似乎无法掌握
perms( xs\\\\[x] )
应该如何运作。 The trace of a two element list shows: 两个元素列表的跟踪显示:
perms [2,3]
[ x:ps | x <- [2,3] , ps <- perms ( [2,3] \\ [x] ) ] exe.1
[ 2:ps | ps <- perms [3] ] ++ [ 3:ps | ps <- perms [2] ] exe.2
...
How do you go from exe.1
to exe.2
? 你怎么从
exe.1
到exe.2
?
Well, it just inserts 2
and 3
respectively into [2,3] \\\\ [x]
. 好吧,它只是分别在
[2,3] \\\\ [x]
插入2
和3
。 So you have 所以你有了
[ 2:ps | ps <- perms ([2,3] \\ [2]) ] ++ [ 3:ps | ps <- perms ([2,3] \\ [3]) ]
And since \\\\
is the difference operator, ie it returns the elements of the first list which are not in the second list, the result is [3]
and [2]
respectively. 并且由于
\\\\
是差值运算符,即它返回第一个列表中不在第二个列表中的元素,结果分别为[3]
和[2]
。
It basically says: 它基本上说:
x
from list xs
( x <- xs
) xs
取任何x
( x <- xs
) ps
that is permutation of list xs\\\\[x]
(ie xs
with deleted x
) - perms ( xs\\\\[x] )
ps
是列表xs\\\\[x]
排列(即xs
与删除的x
) - perms ( xs\\\\[x] )
the perms(xs\\\\[x])
is recursive call that deletes x
from xs
. perms(xs\\\\[x])
是从xs
删除x
递归调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.