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
Benchmarks against imperative languages
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Martin Jambon <martin_jambon@e...>
Subject: Re: [Caml-list] Looking for suggestions on self-referential object definitions
On Sat, 4 Mar 2006, David Powers wrote:

> I am in the middle of hacking together a rogue-like game in OCaml for fun and 
> to get a better feel for the language, and I have come across a stumbling 
> block.  Specifically I began to model items in the game as objects deriving 
> from a base item class.  All well and good until I tried to come up with a 
> way to model a container (like a backpack, or sack).  The container itself 
> was an item, that could hold other items - including, possibly, other 
> containers.
> Some brief dabbling led me to the idea that I could store the items in the 
> container in a list using a variant type to differentiate the specific types 
> of items - but I can't for the life of me think how to add containers to that 
> type list without having defined containers first.  I've included the simple 
> code below so that hopefully some smart person can point out how dumb I'm 
> being.  ;)
> -David

What you are doing is correct, you just need to tell the compiler about 
the type of the items.
There are a several ways of doing this, here is one:

class virtual item =
    object (self)
      val mutable name = ""

      method name = name

      method set_name newname = name <- newname

class weapon =
    object (self)
      inherit item

type 'a item = [ `Container of 'a
 	       | `Weapon of weapon ]

class container =
    object (self)
      inherit item

      val mutable items : container item list = []

      method add newitem = items <- (newitem :: items)

      method contents = items

      method remove i = items <- List.filter (fun x -> x != i) items

      method contents_to_string =
        let print_item i =
          match i with
            | `Weapon w -> Printf.sprintf "%s (weapon)" w#name
            | `Container c -> Printf.sprintf "%s (container) -
Containing:\n%s" c#name c#contents_to_string
          String.concat "\n" ( print_item items)


Another possibility is to define the type of the objects without defining 
a class or class type, so that you can write directly a recursive type 
definition separately from the class definition:

type obj = < content : item list >
and item = [ `A | `B of obj ]

(* BTW I don't know how to tell the compiler that the class creates
    objects of type obj, but this can be done: *)
class c = object method content : item list = [] end


Martin Jambon, PhD

Visit, bioinformatics wiki