How to associate an iterator with a collection in OCaml

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 specific ['a] queuesubtype collectionand ['a] iterator_queuesubtype classes iterator.

I mainly want to know how to define a method iterator : unit -> 'a iterator, because I do not see how these two types can be related. Do I need to ['a] iterator_queueinherit from both abstract ones? or I have to act differently.

+5
source share
2 answers

Probably the easiest way to do this is to define the iterator as an object as part of the queue definition (in Java this will be called the "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

, lst () q iterator. .

+4

, - .

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

All Articles