[Haskell-beginners] Type classes are not like interfaces, after all

Brandon S. Allbery KF8NH allbery at ece.cmu.edu
Sat Jan 24 00:14:06 EST 2009

On 2009 Jan 23, at 8:37, Francesco Bochicchio wrote:
> I think I get the polymorphism. What I don't get is why a  
> specialized type cannot
> replace a more generic type, since the specialized type implements  
> the interface
> defined in the generic type.

Try it this way.  The declaration

 > a :: Num n => n
 > a = 3 :: Integer

is not the same as

>  AbstractInterface a = new ConcreteClass();

because Integer doesn't implement *all* of Num, in particular nothing  
needed for the Float, Double, or Complex instances.  In a sense,  
instances in Haskell are inverses of interfaces in Java; in Java you  
accept more specific but in Haskell you accept *less* specific.  This  
is because an instance actually asserts a "for all possible matching  
types" requirement, whereas Java asserts an "any matching type"  
requirement.  (Pedantically:

 > a :: forall n. Num n => n

You don't have to write (and in Haskell 98, can't write, just as in  
Java you can't explicitly write "forany" in an interface definition)  
the "forall"; in Haskell98 (and Java respectively) it's there by  
definition, in Haskell extensions it's implied for top level types for  
backward compatibility.)

In many cases you can treat the two the same because the member types  
happen to have an exact relationship such that "forall" and "forany"  
are both satisfied, but Num is too wide (and far too complex; the  
ideal structure of the Haskell numeric classes is constantly  
debated).  So the equivalence of typeclasses and interfaces is a "most  
of the time" thing, not a definition or requirement.

brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery at kf8nh.com
system administrator [openafs,heimdal,too many hats] allbery at ece.cmu.edu
electrical and computer engineering, carnegie mellon university    KF8NH

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20090124/e9014272/attachment.htm

More information about the Beginners mailing list