【问题标题】:How to associate an iterator to a collection in OCaml如何将迭代器关联到 OCaml 中的集合
【发布时间】:2010-01-02 22:42:23
【问题描述】:

我在 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] queuecollection 子类型和['a] iterator_queue iterator 的子类型。

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

【问题讨论】:

    标签: class collections iterator ocaml


    【解决方案1】:

    可能最简单的方法是将迭代器定义为队列定义范围内的对象(在 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 是在调用iterator 时对q 的(不可变)值的引用。对队列的后续更改不会反映在迭代器中。

    【讨论】:

    • 我想到的方法之一就是这样做,但这是考试的主题,我正在努力寻找解决方案;)
    【解决方案2】:

    我怀疑这可能只是对相互递归的类定义的测试。

    class ['a] queue = 
      object
        inherit 'a container
        method iterator = new iterator_queue args
        ...
      end
    and ['a] iterator_queue args = 
      object
        ...
      end
    

    【讨论】:

      猜你喜欢
      • 2011-10-07
      • 2020-09-14
      • 2017-06-18
      • 1970-01-01
      • 2022-08-17
      • 2011-05-02
      • 2017-08-02
      • 2011-11-10
      • 2021-12-14
      相关资源
      最近更新 更多