这个使用列表理解来计算排列的 Haskell 函数是如何工作的?

发布于 2024-09-13 04:23:46 字数 482 浏览 6 评论 0原文

我正在阅读 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

就是爱搞怪 2024-09-20 04:23:47

它基本上是这样说的:

  1. 从列表 xs 中取出任意 x (x <- xs)
  2. 取出 ps 进行排列列表 xs\\[x](即删除了 xxs) - perms ( xs\\[x] )< /code>
  3. 返回结果。

perms(xs\\[x]) 是从 xs 中删除 x 的递归调用。

It basically says:

  1. Take any x from list xs (x <- xs)
  2. Take ps that is permutation of list xs\\[x] (i.e. xs with deleted x) - perms ( xs\\[x] )
  3. Return the result.

the perms(xs\\[x]) is recursive call that deletes x from xs.

我们只是彼此的过ke 2024-09-20 04:23:47

好吧,它只是将 23 分别插入到 [2,3] \\ [x] 中。所以你有

[ 2:ps | ps <- perms ([2,3] \\ [2]) ] ++ [ 3:ps | ps <- perms ([2,3] \\ [3]) ]

And 因为 \\ 是差异运算符,即它返回第一个列表中不在第二个列表中的元素,结果是 [3] 并且分别为[2]

Well, it just inserts 2 and 3 respectively into [2,3] \\ [x]. So you have

[ 2:ps | ps <- perms ([2,3] \\ [2]) ] ++ [ 3:ps | ps <- perms ([2,3] \\ [3]) ]

And 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文