所以我在玩 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 甚至会让我创建这个实例吗?
最佳答案
所以,你需要定义 Foldable Set
.这意味着你不能依赖 a
, 自 foldr
需要为任何 a
工作.
所以基本上你需要将约束类型嵌入到 Foldable
的定义中。为了使这项工作,我想。
请注意 Data.Set.foldr
没有 Ord a
约束,因此它可以定义 Foldable
实例。
关于haskell - Haskell 中类型类实例的类型约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26689686/