Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] [Q]: Co(ntra)variance and subtyping?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Mark Wotton <mrak@c...>
Subject: Re: [Caml-list] [Q]: Co(ntra)variance and subtyping?
On Fri, 16 Nov 2001, Clemens Hintze wrote:

> Two things I would like to ask you right now:
> - What does subtyping exactly mean in OCaml resp. functional
>   programming?
> - What means covariance and contravariance of types and subtypes?

Not being an Ocaml guru, I shan't attempt the first question.
The second's pretty easy, though: covariance is the sane way of doing OO,
and contravariance is bizarre. (Right, if there's any Eiffel devotees on
here, I've just started a flamewar. :)

Seriously: contravariance breaks the assumption that a subtype is capable
of everything that its parent can do. Essentially, it allows you to narrow
arguments to functions: to use some weird eiffelish pseudocode i had
lying around, you can do this.

class bar

class bar_child is bar

class garment public foo(b: bar ) 
class toga is garment public foo(b: bar_child)
/* narrowing the argument of foo */

class tester public main = let p:garment = toga{} in{})
/* attempting to call foo method of toga object using object of type bar:
   fails at runtime */

Basically, you expect to be able to call "foo" on any garment, and the
only requirement is that the argument be of type "bar". "toga" narrows it
to "bar_child" and the whole thing falls down in a heap.

Covariance doesn't let this happen. You can actually widen the type in a
child class, I believe: this isn't generally particularly useful, though.

> Regards,
> Clemens.
> PS: Sorry, if my english is not flawless, but it is not my
>     mother-tongue, and I do not speak french a bit, unfortunately.

It's an odd thing: most of the posts with apologies for bad English I've
seen on Usenet have been flawless as far as composition goes.


Bug reports:  FAQ:
To unsubscribe, mail  Archives: