haskell - Haskell 中类型类实例的类型约束?

标签 haskell typeclass type-constraints

所以我在玩 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/

相关文章:

typescript - 如何输入对应类型的元组数组?

haskell - 为什么我的 ByteString 在我的 x86_64 架构上是 BigEndian 格式?

haskell - 在 Haskell 中执行断言

haskell - 具有多个子字段的数据类型的实例方程

locale - 如何在不收到警告且不使用类型类的情况下重载符号?

c# - 如何将泛型约束为枚举类型?

f# - 为什么空检查会导致 F# 中的等式约束?

haskell - 为什么使用 rdeepseq 不足以在关闭句柄之前完成读取?

scala - 如何匹配没有特定类型类实例的类型?

haskell - 创建完全依赖的串联