所以我正在玩Data.Set.Monad,它似乎不是像Data.Foldable那样Data.Set的实例。我决定尝试自己添加这个实例作为实验:
import Data.Foldable (Foldable, foldr)
import qualified Data.Set.Monad as S (Set, foldr)
instance Foldable S.Set where
foldr = S.foldr
我收到编译错误:
No instance for (Ord a) arising from a use of ‘S.foldr’
Possible fix:
add (Ord a) to the context of
the type signature for foldr :: (a -> b -> b) -> b -> Set a -> b
In the expression: S.foldr
In an equation for ‘foldr’: foldr = S.foldr
In the instance declaration for ‘Foldable Set’
好的,这必须是因为S.foldr :: Ord a => (a -> b -> b) -> b -> Set a -> b
。如何在实例声明中表达此约束?我试过这个:
instance (Ord a) => Foldable (Set a) where
foldr = S.foldr
并获得另一个编译错误:
The first argument of ‘Foldable’ should have kind ‘* -> *’,
but ‘Set a’ has kind ‘*’
In the instance declaration for ‘Foldable (Set a)’
我做错了什么?或者Haskell甚至会让我创建这个实例吗?
答案 0 :(得分:7)
因此,您需要定义Foldable Set
。这意味着您无法依赖a
,因为任何 foldr
需要a
。
所以基本上你需要将约束种类嵌入到Foldable
的定义中,以使这项工作成为可能。我想。
请注意,Data.Set.foldr
没有Ord a
约束,因此可以定义Foldable
个实例。