Can you make an instance of a class not for a type but for a whole class in Haskell?

你说的曾经没有我的故事 提交于 2020-01-01 09:04:13

问题


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.


回答1:


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.)




回答2:


GHC allows your definition with some language extensions enabled

{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}

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

This makes 2 <> 3 result in 5.

But this overlaps with other Monoid instances, so trying to evaluate "Hello" <> "World" results with an error: Overlapping instances for Monoid [Char]

So, I think that the short answer is: no.



来源:https://stackoverflow.com/questions/32769112/can-you-make-an-instance-of-a-class-not-for-a-type-but-for-a-whole-class-in-hask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!