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] Mutual recursion between classes and types in OCaml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2003-06-23 (01:14)
From: Jacques Garrigue <garrigue@k...>
Subject: Re: [Caml-list] Mutual recursion between classes and types in OCaml
From: Anton Lavrik <>

> I suppose it's quite useful to define object types and "ordinary" types, so
> that they could refer to each other. For example,
> 	class c = 
> 	object val v = A 0	(* constructor `A' is not bound *)
> 	end 
> 	[...] (* some syntactic construct like `and' keyword *)
> 	type t = A of int | B of c (* now type `t' and constructor `A' are
> 	defined *)

The solution is a FAQ, you just have to parameterize your datatype
with the type of the class (opening the recursion), and everything
will be fine.
> So why mutual recursion between classes and types is not allowed? Is this
> fundamental or technical problem? I can't find any references denoting that
> problem.

This is technical, but has theoretical implications too.
Technical problem: typing of classes definitions and type definitions
are completely independent, and both of them are rather
complex. Mixing the two is practically hard.
Semantical problem: the handling of constraints in type definitions
and class definitions is different. Types allow polymorphic
recursion, and you must give all the constraints explicitely for
every type (what you write in the .mli is the real type). With
classes, constraints are propagated silently (so they may be only
implicit in the .mli), and there is no polymorphic recursion.
Mixing the two might be confusing, or unsound.

> BTW, what does `-rectypes' ocamlc's option really mean (there are quite a
> few words about it in reference manual)? And how does it concern the
> subject?

This is unrelated. It allows you two build arbitrary recursive types
through type inference
# let rec depth (_,l) = 1 + List.fold_left max 0 ( depth l);;
val depth : ('b * 'a list as 'a) -> int = <fun>
#  depth (1,[2,[];3,[]]);;
- : int = 2

Jacques Garrigue      Kyoto University     garrigue at
		<A HREF=>JG</A>

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