Personal tools

Multiple instances

From HaskellWiki

Revision as of 15:34, 20 January 2009 by Lemming (Talk | contribs)

Jump to: navigation, search

1 Question

I like to define multiple type class instances for the same pair of class and type. How is it possible?

2 Answer

You can achieve it if you keep class and type definitions in other modules than the instance declarations. These instances are then called orphan instances. However you won't be lucky with this solution, since you must ensure, that two modules with conflicting instances declarations are never imported together, since instance declarations are automatically imported and cannot be hidden. Even more also modules which import conflicting modules only indirectly conflict itself. It is also not possible to define instances with respect to different type parameter orders,

as it is required for type constructor classes like
Functor
,
Monad
, and others.

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


3 See also