How to associate an iterator to 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 concrete classes ['a] queue
subtype of collection
and ['a] iterator_queue
a subtype of iterator
.
I want mainly to know h开发者_运维问答ow 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.
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.
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
精彩评论