Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to associate an iterator to a collection in OCaml

Tags:

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.

like image 797
0xFF Avatar asked Jan 02 '10 22:01

0xFF


People also ask

What is :: In OCaml?

:: means 2 camel humps, ' means 1 hump! – Nick Craver. Feb 27, 2010 at 12:09. Ok a decent comment: merd.sourceforge.net/pixel/language-study/… I don't use oCaml, but there's a full syntax list you my find useful, even if there's no real context to it.

What does list Fold_left do in OCaml?

So fold_left is "folding in" elements of the list from the left to the right, combining each new element using the operator.

What does list ITER do OCaml?

I.e., List. iter is for when you just want to call a function that doesn't return anything interesting. In your example, Printf. printf in fact doesn't return an interesting value (it returns () ).

What does list map do in OCaml?

Ocaml's List. map function is the same as the map defined above. The map function is a list transformer: it takes a list as an input and returns another list as an output.


2 Answers

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.

like image 143
Chris Conway Avatar answered Oct 03 '22 21:10

Chris Conway


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
like image 32
Victor Nicollet Avatar answered Oct 03 '22 23:10

Victor Nicollet