views:

107

answers:

2

I have these two classes in OCaml

class type ['a] collection =
  object
    method add : 'a -> unit
    method clear : unit -> unit
    method iterator : unit -> 'a iterator
    method remove : 'a -> unit
  end

class type ['a] iterator =
  object 
    method hasNext : unit -> bool 
    method next : unit -> 'a 
  end

And I need to create two concrete classes ['a] queue subtype of collection and ['a] iterator_queue a subtype of iterator.

I want mainly to know how to define the method iterator : unit -> 'a iterator because I don't see how the two types can be connected, Does the ['a] iterator_queue has to be inherited from both the abstract ones? or should I proceed differently.

Thank you.

+4  A: 

Probably the easiest way to do this is to define the iterator as an object within the scope of the definition of the queue (in Java, this would be called an "inner class"). For example:

class ['a] queue : ['a] collection = 
  object
    val q = ref []

    (* definitions of add, clear, remove *)

    method iterator () : 'a iterator =
      object
        val lst = ref !q

        (* definitions of hasNext and next *)

      end
  end

Note that lst is a reference to the (immutable) value of q at the time that iterator is called. Subsequent changes to the queue won't be reflected in the iterator.

Chris Conway
One of the ways I thought of was doing so, but this is a subject of an exam, which I'm trying to find the solution for ;)
martani_net
+1  A: 

I suspect this might simply be a test of mutually recursive class definitions.

class ['a] queue = 
  object
    inherit 'a container
    method iterator = new iterator_queue args
    ...
  end
and ['a] iterator_queue args = 
  object
    ...
  end
Victor Nicollet