Personal tools

Multiple instances

From HaskellWiki

Jump to: navigation, search

1 Question

I like to define multiple type class instances for the same pair of class and type. Sometimes I also need two instances where the order of type parameters is different.

E.g. I want to define two
instances for a pair:

One instance where the first member is mapped and another instance where the second member is mapped. How is it possible?

2 Answer

You can define multiple type class instances for the same pair of class and type if you keep the class and type definitions in different modules, i.e. not the modules than contains the instance declarations. These instances are therefore called orphan instances.

However this isn't perfect, since you must ensure that two modules with conflicting instances declarations are never imported together because instance declarations are automatically imported and cannot be hidden.

Furthermore, modules which import conflicting modules only indirectly conflict itself.

Thus multiple instances should be avoided, and a safe way to do this is to avoid orphan instances. You can achieve this by wrapping the type in a
and lift all required instances to that new type.

If you do not fear language extensions you can simplify this task considerably using the GeneralizedNewtypeDeriving feature. The custom instance can be defined for the class/newtype pair and it is not orphan if it is defined where newtype is introduced.

you can also change the order of type parameters or give type parameters a fixed type.

Example: There are so many types and operations that exhibit a monoid structure,

but it would not be useful to call all the operations
. It is however useful to call them via the Monoid interface sometimes, e.g. in the
monad. Thus the module
provides several newtype wrappers for common monoids.

3 See also