简体   繁体   English

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

[英]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.1exe.2

Well, it just inserts 2 and 3 respectively into [2,3] \\\\ [x] . 好吧,它只是分别在[2,3] \\\\ [x]插入23 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: 它基本上说:

  1. Take any x from list xs ( x <- xs ) 从列表xs取任何xx <- xs
  2. Take ps that is permutation of list xs\\\\[x] (ie xs with deleted x ) - perms ( xs\\\\[x] ) ps是列表xs\\\\[x]排列(即xs与删除的x ) - perms ( xs\\\\[x] )
  3. Return the result. 返回结果。

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.

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