class - 如何将迭代器关联到 OCaml 中的集合

标签 class collections iterator ocaml

我在 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/

相关文章:

swift - 访问子类时不能在类型错误的实例上使用静态成员

forms - Play 2 : idiomatic approach to binding a form to List[Model]

java - 如何一次删除不同的可更新记录?

c++ - 指针列表 C++

C++ 列表迭代器无法初始化

c++ - 模板函数中任意迭代器的值类型

C++ 指向类对象的指针

c++ - C++ 构造函数中的混淆

c++ - C++中一些基本的继承问题

java - 我应该迭代一个 Java 集合来获取子集,还是应该先将它转换为数组然后迭代来获取它?