List haskell中的列表置换
所以我是哈斯克尔的新手,我已经玩了一段时间了。我想得到输出所有列表排列的函数。我已经写了两个实现,一个运行良好,另一个给我一个错误。任何帮助都会很棒 这是第一个(工作)实施:List haskell中的列表置换,list,haskell,permutation,List,Haskell,Permutation,所以我是哈斯克尔的新手,我已经玩了一段时间了。我想得到输出所有列表排列的函数。我已经写了两个实现,一个运行良好,另一个给我一个错误。任何帮助都会很棒 这是第一个(工作)实施: permute [] = [[]] permute xs = [y| x <- xs, y <- map (x:) $ permute $ delete x xs] 下面是错误消息: Occurs check: cannot construct the infinite type: t0 = [t0] Exp
permute [] = [[]]
permute xs = [y| x <- xs, y <- map (x:) $ permute $ delete x 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)'
如果有人能解释我为什么会犯这个错误,我将不胜感激。感谢使用类型签名使编译器的工作更轻松
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
使用类型签名可以简化编译器的工作
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
如果您不确定是否有一个类型
派生Eq
(需要使用删除
),可以使用类似的方法:
也许这是一种过度使用:)如果您不确定是否有一个类型
派生Eq
(需要使用删除):
也许这是一种过激:)谢谢,这很有道理。谢谢,这很有道理。请注意,使用delete
的方法效率很低。感谢大家的提醒,我计划在数据中查看实现。列表请注意,使用delete
的方法效率很低。谢谢大家的提醒,我计划在Data.List中检查实现