Version française
Home     About     Download     Resources     Contact us    
Browse thread
recursive types
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jeremy Yallop <jeremy.yallop@e...>
Subject: Re: [Caml-list] recursive types
Jacques Le Normand wrote:
> is it possible to have mutually recursive classes and types?

Yes, using recursive modules.  The syntax is a little heavy, though, 
since you have to write some of the definitions in both the signature 
and the implementation.

> class type node_wrapper =
> object
>   method identify : string
>   method get_child_location : location
> end
> 
> class virtual nodeable =
> object(self)
>   method virtual to_node_wrapper : node_wrapper
> end
> 
> type path = (nodeable list * location * nodeable list) option
> and location = Loc of nodeable * path

This might be written as

   module rec M :
   sig
     class type node_wrapper =
     object
       method identify : string
       method get_child_location : M.location
     end

     class virtual nodeable :
     object
       method virtual to_node_wrapper : node_wrapper
     end

     type path = (nodeable list * M.location * nodeable list) option
     type location = Loc of nodeable * path
   end =
   struct
     class type node_wrapper =
     object
       method identify : string
       method get_child_location : M.location
     end

     class virtual nodeable =
     object
       method virtual to_node_wrapper : node_wrapper
     end

     type path = (nodeable list * M.location * nodeable list) option
     type location = Loc of nodeable * path
   end

The definitions which merely define type aliases (node_wrapper and path) 
can be shortened in the implementation section if you prefer:

   module rec M :
   sig
      [elided]
   end =
   struct
     class type node_wrapper = M.node_wrapper

     class virtual nodeable =
     object
       method virtual to_node_wrapper : node_wrapper
     end

     type path = M.path
     type location = Loc of nodeable * path
   end

Jeremy.