列出haskell中的排列

时间:2012-07-06 08:54:06

标签: list haskell permutation

所以我是哈斯凯尔的新手,我已经玩了一段时间了。我想让我的函数输出所有列表排列工作。我写了2个实现,一个很好用,另一个给我一个错误。任何帮助都会很棒。

这是第一个(工作)实施:

permute [] = [[]]
permute xs = [y| x <- xs, y <- map (x:) $ permute $ delete x xs]

这个给我一个错误:

permute [] = [[]]
permute xs = map (\x -> map (x:) $ permute $ delete x xs) xs

这是错误信息:

Occurs check: cannot construct the infinite type: t0 = [t0]
Expected type: [t0]
Actual type: [[t0]]
In the expression: map (x :) $ permute $ delete x xs
In the first argument of `map', namely
`(\ x -> map (x :) $ permute $ delete x xs)'

如果有人能解释我为什么会收到这个错误,我会很感激。感谢

2 个答案:

答案 0 :(得分:5)

使用类型签名使编译器的生活更轻松。

permute :: Eq a => [a] -> [[a]],现在我们有:

Couldn't match type `a' with `[a]'
  `a' is a rigid type variable bound by
      the type signature for permute :: Eq a => [a] -> [[a]]
      at perm.hs:4:1
Expected type: [a]
  Actual type: [[a]] 
In the expression: map (x :) $ permute $ xs
In the first argument of `map', namely
  `(\ x -> map (x :) $ permute $ xs)'

因此,我们似乎需要使用concatMap代替map

permute :: Eq a => [a] -> [[a]]
permute [] = [[]]
permute xs = concatMap (\x -> map (x:) $ permute $ delete x xs) xs

答案 1 :(得分:0)

如果您不确定类型app.on('certificate-error', (event, webContents, link, error, certificate, callback) => { if ('yourURL/api/'.indexOf(link) !== -1) { // Verification logic. event.preventDefault(); callback(true); } else { callback(false); } }); (请求使用deriving Eq),则可以使用此类内容:

delete

也许这太过分了:)