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 classes are impossible?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: james woodyatt <jhw@w...>
Subject: Re: [Caml-list] Recursive classes are impossible?
On Monday, June 24, 2002, at 02:34 PM, Gerd Stolpmann wrote:
> No, this is not the problem. Try the following:
> class tree =
> object(self:'self)
>   val mutable v = (None : int option)
>   val mutable ch = ([] : 'self list)
>   method get = v
>   method set x = v <- x
>   method children = ch
>   method set_children x = ch <- x
> end
> This definition works at the first glance, but if you try to
> inherit from this class and subtype this class at the same
> time, you will run into problems.
> class broccoli =
> object
>   inherit tree
>   method color = "green"
> end

Here's a more graphic explanation of why this is a bad idea:

	let t = new tree;;
	let b = new broccoli;;
	(b :> tree)#set_children [t];;

Here, the compiler-- quite sensibly-- errors on the coercion.

The "set_children" method of class tree takes a list of tree objects.  
The "set_children" method of class broccoli takes a list of broccoli 
objects.  If you were able to coerce a broccoli object into a tree 
object, you could then set its children to a list of non-broccoli tree 
objects-- which would violate the invariant for objects of the broccoli 

j h woodyatt <>

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