Haskell style & typeclass design (should typeclasses be minimized?)

Suppose that

class A a where
   m1 :: a -> a 
   m2 :: a -> a
   m3 :: a -> a
   ...

where it is possible to write default implementation for m2 and m3 by using m1.

Is it better to leave m2 and m3 into A or write them as extra functions m2 :: A a => a -> a outside A? Or in other words, is worth to minimize the class API or does it matter?

I checked (quickly) some style guides, like programmin guidelines and some of the links in large-scale design-question, and some books (craft & rwh), but couldn't find a recommendation to this one. If there are presentations, blogs or books covering this kind of issues, please, could you share some pointers?

Email-list thread type class design discusses this and might emphasize minimizing.


Keep them in the class if

  • There are multiple different sets of minimal complete definitions for that class, and you can't a priori tell which is more simple/elegant for a given instance.
  • It can reasonably be expected that particular types (eg unboxed vectors) will allow more efficient implementations of m2 and m3 than the default one. If these aren't overridable as methods, you'd need to resort to rewrite rules for this kind of optimisation.
  • An example of a standard class with a great many “superfluous” methods is (in more recent versions) Foldable . This is in part due to historical reasons, but also because different containers can have very different stricness etc. properties, so the default implementations of some methods might be really bad for performance of some instances.

    If neither of these considerations applies to your class, keep m2 and m3 out of the class. (You can always put them in later: if you provide a default implementation, it won't break anybody's code.)

    链接地址: http://www.djcxy.com/p/42880.html

    上一篇: 功能性,动态性和方面性的模式

    下一篇: Haskell风格和类型设计(应该最小化类型类?)