Version française
Home     About     Download     Resources     Contact us    
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 
class.


--
j h woodyatt <jhw@wetware.com>

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners