你能否让一个类的实例不是为了一个类型,而是为了Haskell中的一个整体类? [英] Can you make an instance of a class not for a type but for a whole class in Haskell?
问题描述
假设我想让所有数字都是 Monoid
的一个实例。而不是像这样为每个 Num
创建一个实例:
实例Monoid Int其中
mappend =(+)
mempty = 0
实例Monoid Float其中
mappend =(+)
mempty = 0.0
- etc
有没有这样的事情?
实例Num t => Monoid t其中
mappend =(+)
mempty = 0
编辑
有些人正在回答GHC的延期问题,并警告有关潜在的问题;我发现信息丰富,但我认为我会坚持 Sum
, Product
以及任何 coerce
。
我将它解释为询问一个普遍的前提,而不是专门关于 也许你可以通过启用语言扩展FlexibleInstances,UndecidableInstances和使用重叠实例来获得你写的东西。 但是你可能不希望:它看起来像 如果 不幸的是,那是不对的。它实际上说的更像是 以下是如何使 因此,如果您编写像这样的实例声明,则不能编写任何其他实例声明。 (至少不是没有 Suppose I want to make all numbers an instance of Is there something like this?
Some are answering with GHC extensions and warning about the potential issues; I found that informative, but I think I will stick with I'm interpreting this as asking about a general premise, rather than specifically about Maybe you could get what you wrote to work, by enabling language extensions FlexibleInstances, UndecidableInstances, and using overlapping instances. But you probably wouldn't want to: it seems like "If Unfortunately, that's not right. What it's actually saying is more like "Here's how to make Thus, if you write an instance declaration like this, you can't write any other instance declarations. (At least not without 这篇关于你能否让一个类的实例不是为了一个类型,而是为了Haskell中的一个整体类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Monoid
和 Num $ c
实例Num t => Monoid t where ...
在说
t
是 Num
,下面是如何使 t
一个 Monoid
...
t
一个 Monoid。
首先, t
必须是 Num
的一个实例。 。
OverlappingInstances
,这会带来它自己的问题。)Monoid
. Instead of having to create an instance for each Num
like this:instance Monoid Int where
mappend = (+)
mempty = 0
instance Monoid Float where
mappend = (+)
mempty = 0.0
-- etc
instance Num t => Monoid t where
mappend = (+)
mempty = 0
Edit
Sum
, Product
and whatever coerce
does.Monoid
and Num
.instance Num t => Monoid t where ...
is saying t
is an instance of Num
, here's how to make t
an instance of Monoid
..." t
an instance of Monoid.
First, it's necessary that t
be an instance of Num
. Next..."OverlappingInstances
, which would bring its own issues.)