I'd like to write an Alternative instance for the Identity newtype. The skeleton isn't hard:
instance Alternative Identity where
empty = _
(<|>) = _
However, the implementation is impossible for all types. It would be easy if I have a Monoid instance for a though:
instance Alternative Identity where
empty = Identity mempty
(Identity a) <|> (Identity a') = Identity (a <> a')
Is there a way to tell the compiler that I want to define the Alternative instance only for when the type inside has a Monoid instance? Since the a isn't mentioned anywhere, I can't just use a constraint Monoid a =>.
An
Alternativemust provideemptyfor all typesa, with no restrictions. Otherwise, it does not fulfill theAlternativecontract.That is, if we have an instance
Alternative f, we must havewithout any further constraints.
Hence,
Identityis not anAlternative.This is a known problem, found in many similar type classes. For instance, many would enjoy a
Functor Setinstance, but that would requirefor all types
aandb, while the function above can only be achieved onOrdtypes. Since we can't add the constraint, we do not get a functor.Still, one can try using a more general type class that accounts for additional constraints. Maybe something like
but these are not the "standard" ones in the library. (I guess on hackage there should be something similar to the constrained class variants above.)