这个使用列表理解来计算排列的 Haskell 函数是如何工作的?
我正在阅读 Simon Thompson 的 Haskell:函数式编程的工艺,我想知道这是如何工作的:
perms [] = [[]]
perms xs = [ x:ps | x <- xs , ps <- perms ( xs\\[x] ) ]
我似乎无法理解 perms( xs\\[x ] )
应该起作用。两个元素列表的跟踪显示:
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
...
如何从 exe.1
转到 exe.2
?
I'm reading Simon Thompson's Haskell: The Craft of Functional Programming, and I'm wondering how does this work:
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. 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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它基本上是这样说的:
xs
中取出任意x
(x <- xs
)ps
进行排列列表xs\\[x]
(即删除了x
的xs
) -perms ( xs\\[x] )< /code>
perms(xs\\[x])
是从xs
中删除x
的递归调用。It basically says:
x
from listxs
(x <- xs
)ps
that is permutation of listxs\\[x]
(i.e.xs
with deletedx
) -perms ( xs\\[x] )
the
perms(xs\\[x])
is recursive call that deletesx
fromxs
.好吧,它只是将
2
和3
分别插入到[2,3] \\ [x]
中。所以你有And 因为
\\
是差异运算符,即它返回第一个列表中不在第二个列表中的元素,结果是[3]
并且分别为[2]
。Well, it just inserts
2
and3
respectively into[2,3] \\ [x]
. So you haveAnd since
\\
is the difference operator, i.e. it returns the elements of the first list which are not in the second list, the result is[3]
and[2]
respectively.