[Haskell-cafe] default function definitions

Andrew Coppin andrewcoppin at btinternet.com
Sat Jul 24 16:43:09 EDT 2010


Patrick Browne wrote:
> Hi,
> I am studying the Haskell type class system as part of a language
> comparison thesis. At this point I am looking at how default function
> definitions are handled in classes. Functions are usually defined in
> instances, not classes. I appreciate that the code below may not be an
> appropriate way to write Haskell programs, but it does help me
> understand how defaults work. I am not trying to construct a running
> program. Any feedback on the questions below and defaults work in
> general would be appreciated.
>   

1. Stop thinking of Haskell "classes" being like normal classes in OOP. 
They are more like what Java calls "interfaces". A type can belong to a 
class, much like in Java any class can implement Runnable (for example).

2. Making one class a "subclass" of another merely means that before a 
type can be made an instance of Y, it must first be an instance of X. 
There is no "inheritance" in Haskell. And no, if Y is a subclass of X, 
it cannot change anything in X, just add new stuff. It merely means that 
if you say "I want something that's an instance of Y" then it's also 
guaranteed to be an instance of X, without you having to manually say so.

3. A default implementation is just what it says on the tin: an 
implementation that will automatically be used if you don't manually 
supply one. The usual reason for this is if there's an implementation 
that will always work, but in some cases there may be a more efficient 
one. The default implementation is then the general version that will 
always work, and when you write instances for other types, you may 
specify a better implementation. The other reason is if X can be defined 
in terms of Y, and Y can be defined in terms of X. Add default 
implementations for both, and when you write an instance you can 
implement whichever one is easiest and use the default for the other.

HTH.



More information about the Haskell-Cafe mailing list