Haskell type classes (and instances) name a collection of functions. (This is one of those obvious-in-hindsight deep thoughts.)
One of the fundamental principles of all computer programming is to be able to name things and reuse them.
Type classes are a lightweight and flexible alternative to object oriented programming. But I wonder if they could be even more lightweight.
One thing you cannot do with instances is locally define them. If a function has context "(Ctx a) => ...", one cannot use a different set of functions for the same concrete type T on different calls: one is limited to the collection named instance Ctx T. The canonical example is "sort" with context Ord; we need a separate function sortBy.
A simple alternative to type classes would to explicitly pass a type's dictionary to every function call that needs it. Maybe this would not be too annoying in conjunction with implicit parameters.
4 comments :
Sounds a lot like ML's functors.
analogy with OO only works for class members typed like "a -> *"
if you have memners typed like "a -> a -> *" or "* -> a" typeclasses does not look like OO anymore
This is actually how agda uses it's instance arguments feature. In particular, see the page on modelling type classes with instance arguments. If you're looking for more information there's also a paper on instance arguments which doesn't seem to be linked from either of those pages.
Julian, thanks for linking to my paper. There's a new URL though:
http://people.cs.kuleuven.be/~dominique.devriese/agda-instance-arguments/
Dominique
Post a Comment