你能否让一个类的实例不是为了一个类型,而是为了Haskell中的一个整体类? [英] Can you make an instance of a class not for a type but for a whole class in Haskell?

查看:97
本文介绍了你能否让一个类的实例不是为了一个类型,而是为了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

解决方案

我将它解释为询问一个普遍的前提,而不是专门关于 Monoid Num

也许你可以通过启用语言扩展FlexibleInstances,UndecidableInstances和使用重叠实例来获得你写的东西。



但是你可能不希望:它看起来像 实例Num t => Monoid t where ... 在说

如果 t Num ,下面是如何使 t 一个 Monoid ...



不幸的是,那是不对的。它实际上说的更像是

以下是如何使 t 一个 Monoid。首先, t 必须是 Num 的一个实例。 。



因此,如果您编写像这样的实例声明,则不能编写任何其他实例声明。 (至少不是没有 OverlappingInstances ,这会带来它自己的问题。)


Suppose I want to make all numbers an instance of 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

Is there something like this?

instance Num t => Monoid t where
  mappend = (+)
  mempty = 0

Edit

Some are answering with GHC extensions and warning about the potential issues; I found that informative, but I think I will stick with Sum, Product and whatever coerce does.

解决方案

I'm interpreting this as asking about a general premise, rather than specifically about Monoid and Num.

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 instance Num t => Monoid t where ... is saying

"If t is an instance of Num, here's how to make t an instance of Monoid..."

Unfortunately, that's not right. What it's actually saying is more like

"Here's how to make t an instance of Monoid. First, it's necessary that t be an instance of Num. Next..."

Thus, if you write an instance declaration like this, you can't write any other instance declarations. (At least not without OverlappingInstances, which would bring its own issues.)

这篇关于你能否让一个类的实例不是为了一个类型,而是为了Haskell中的一个整体类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆