Default method implementation: Difference between revisions
(no new super-classes) |
m (typo and grammar fixes) |
||
Line 1: | Line 1: | ||
It's always a design question, whether to provide default implementions of methods of [[Type class]]es and how to | It's always a design question, whether to provide default implementions of methods of [[Type class]]es and how to design them. | ||
Here are some suggestions: | Here are some suggestions: | ||
* Make only [[slim instance declaration|trivial]] default implementations. | * Make only [[slim instance declaration|trivial]] default implementations. | ||
* Check, that default implementations | * Check, that default implementations do not introduce type class dependencies, that are not necessary otherwise | ||
: E.g. if you have a <hask>Monad</hask> constraint, but no <hask>Functor</hask> constraint, then use <hask>liftM</hask> instead of <hask>fmap</hask>. | : E.g. if you have a <hask>Monad</hask> constraint, but no <hask>Functor</hask> constraint, then use <hask>liftM</hask> instead of <hask>fmap</hask>. | ||
* 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. | * 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. |
Revision as of 18:07, 13 November 2006
It's always a design question, whether to provide default implementions of methods of Type classes and how to design them.
Here are some suggestions:
- Make only trivial default implementations.
- Check, that default implementations do not introduce type class dependencies, that are not necessary otherwise
- E.g. if you have a
Monad
constraint, but noFunctor
constraint, then useliftM
instead offmap
.
- 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
, andmod
should implement the defaults, wheredivMod
callsdiv
andmod
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
andmod
)"
- 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