简体   繁体   English

在Haskell中输入对类型类实例的约束?

[英]Type constraints on typeclass instances in Haskell?

So I was playing around with Data.Set.Monad , which does not seem to be an instance of Data.Foldable like Data.Set is. 所以我正在使用Data.Set.Monad ,它似乎不像Data.Set那样Data.Foldable的实例。 I decided to try and add this instance myself as an experiment: 我决定尝试自己添加这个实例作为实验:

import Data.Foldable (Foldable, foldr)
import qualified Data.Set.Monad as S (Set, foldr)

instance Foldable S.Set where
  foldr = S.foldr

I get compilation error: 我收到编译错误:

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’

Okay, this must be because S.foldr :: Ord a => (a -> b -> b) -> b -> Set a -> b . 好吧,这必须是因为S.foldr :: Ord a => (a -> b -> b) -> b -> Set a -> b How do I express this constraint in the instance declaration? 如何在实例声明中表达此约束? I tried this: 我试过这个:

instance (Ord a) => Foldable (Set a) where
  foldr = S.foldr

And get another compilation error: 并获得另一个编译错误:

The first argument of ‘Foldable’ should have kind ‘* -> *’,
  but ‘Set a’ has kind ‘*’
In the instance declaration for ‘Foldable (Set a)’

What am I doing wrong? 我究竟做错了什么? Or will Haskell even let me create this instance at all? 或者Haskell甚至会让我创建这个实例?

So, you need to define Foldable Set . 因此,您需要定义Foldable Set Which means you can't depend on a , since foldr is required to work for any a . 这意味着你不能依赖a ,因为foldr需要为任何 a工作。

So basically you would need constraint kinds to be embedded into the definition of Foldable to make this work, I think. 因此,基本上你需要将约束种类嵌入到Foldable的定义中才能使这项工作成为可能。

Note that Data.Set.foldr doesn't have the Ord a constraint so it can define a Foldable instance. 请注意, Data.Set.foldr没有Ord a约束,因此它可以定义Foldable实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM