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.
:: 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.
So fold_left is "folding in" elements of the list from the left to the right, combining each new element using the operator.
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 () ).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With