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] Recursive class types (long-standing question ...)
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2004-01-10 (04:42)
From: Jacques Garrigue <garrigue@k...>
Subject: Re: [Caml-list] Recursive class types (long-standing question ...)
From: William Chesters <>

> Here's something I've wondered about for a while and just encountered again.
> How come this class ..
>     class virtual ['a] c = object
>       method virtual b: bool c
>     end
> ... gets a constraint 'a = bool?  I.e. for instance this doesn't compile:
>     class virtual ['a] c = object
>       method virtual b: bool c
>       method virtual i: int c
>           (* "This type int should be an instance of type bool" *)
>     end

This is almost a FAQ.
The deep reason is that ocaml object types are defined by structure,
and as a result only regular recursion is allowed. If we were to allow
polymorphic recursion in class types as required by your example, the
type could not be represented as a regular tree anymore.
(to be fully exact, in this particular case it is possible to
represent it as a regular tree, but this would break the stronger
invariant used by the compiler, which requires all occurences of a
type in its own expansion to have the same parameters)

Note that this applies only to structural types.
For defined types you can use polymorphic recursion.

type 'a t = { b: bool t }

> Note that the following does work in C++:
>     template <class a>
>     struct c {
>       virtual c<bool> b() = 0;
>       virtual c<int> i() = 0;
>     };
> I guess there are workarounds but it seems unnecessary that ML should find
> recursive parameterised classes harder than C++?

In C++ classes are not equal by structure, so the second case applies.

Jacques Garrigue

To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: