Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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.

like image 443
Gspia Avatar asked Aug 12 '16 11:08

Gspia


1 Answers

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 (e.g. 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.)

like image 59
leftaroundabout Avatar answered Nov 06 '22 11:11

leftaroundabout