Default method implementation

From HaskellWiki
Revision as of 17:12, 13 November 2006 by Lemming (talk | contribs) (no new super-classes)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

It's always a design question, whether to provide default implementions of methods of Type classes and how to desing them.

Here are some suggestions:

  • Make only trivial default implementations.
  • Check, that default implementations does not introduce type class dependencies, that are not necessary otherwise
E.g. if you have a Monad constraint, but no Functor constraint, then use liftM instead of fmap.
  • If you have the choice, whether to implement the method default by custom code or by calling other methods of the same class, call methods of the same class. This reduces the amount of implementation work for class instances. It also makes it more probable, that no extra super-classes are needed.
E.g. the default methods of the class providing divMod, div, and mod should implement the defaults, where divMod calls div and mod and vice versa.
Do not try to implement mod by repeated subtraction or so.
  • Document which methods must be implemented at least.
E.g. "instances must implement divMod or (div and mod)"
  • Instance implementations should not call other methods of the same class with respect to instantiated type.


See also

http://www.haskell.org/pipermail/haskell-cafe/2006-November/019329.html