tur*_*ete 0 haskell list permutation
所以我是哈斯凯尔的新手,我已经玩了一段时间了.我想让我的函数输出所有列表排列工作.我写了2个实现,一个很好用,另一个给我一个错误.任何帮助都是极好的.
这是第一个(工作)实现:
permute [] = [[]]
permute xs = [y| x <- xs, y <- map (x:) $ permute $ delete x xs]
Run Code Online (Sandbox Code Playgroud)
这个给我一个错误:
permute [] = [[]]
permute xs = map (\x -> map (x:) $ permute $ delete x xs) xs
Run Code Online (Sandbox Code Playgroud)
这是错误信息:
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)'
Run Code Online (Sandbox Code Playgroud)
如果有人能解释我为什么会收到这个错误,我会很感激.谢谢
使用类型签名可以使编译器的生活更轻松.
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)'
Run Code Online (Sandbox Code Playgroud)
所以,似乎我们需要使用concatMap而不是map.
permute :: Eq a => [a] -> [[a]]
permute [] = [[]]
permute xs = concatMap (\x -> map (x:) $ permute $ delete x xs) xs
Run Code Online (Sandbox Code Playgroud)