如何将迭代器与OCaml中的集合相关联

0xF*_*xFF 5 collections ocaml iterator class

我在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
Run Code Online (Sandbox Code Playgroud)

我需要创建两个具体类['a] queue子类型collection['a] iterator_queue子类型iterator.

我想主要知道如何定义方法,iterator : unit -> 'a iterator因为我没有看到这两种类型是如何连接的,是否['a] iterator_queue必须从两个类型继承?或者我应该采取不同的行动

Chr*_*way 4

也许最简单的方法是将迭代器定义为队列定义范围内的对象(在 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
Run Code Online (Sandbox Code Playgroud)

请注意,这是对调用时lst的(不可变)值的引用。对队列的后续更改不会反映在迭代器中。qiterator