我在 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
我需要创建两个具体的类
['a] queue
collection
的子类型和 ['a] iterator_queue
iterator
的子类型.我主要想知道如何定义方法
iterator : unit -> 'a iterator
因为我没有看到这两种类型如何连接,是否['a] iterator_queue
必须从两个抽象的继承?或者我应该以不同的方式进行。
最佳答案
可能最简单的方法是将迭代器定义为队列定义范围内的对象(在 Java 中,这将称为“内部类”)。例如:
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
叫做。对队列的后续更改不会反射(reflect)在迭代器中。
关于class - 如何将迭代器关联到 OCaml 中的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1993137/