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.
Sum
andProduct
(see Data.Monoid)Sum
, I can do this:mconcat ([1,2] :: Sum Int)
, which is nice, but I can't domconcat ([1,2] :: Sum Float)
, normconcat ([1,2] :: Sum Fractional)
. What is the proper way to useSum
forFloat
s andDouble
s?mconcat ([1,2] :: [Sum Float])
works fine for me ;)Fractional
is no type, it's a class, soSum Fractional
makes no sense here (Sum
wants something of kind*
as it's first parameter, butFractional
is* -> Constraint
):: [Sum Int]
in the first example not:: Sum Int
. And what I couldn't get to work wasmconcat ([1.0, 2.0] :: [Sum Float])
;mconcat ([1, 2] :: [Sum Float])
works fine.