2010-01-02 11 views
5

의 컬렉션에 반복자를 연결하는 데 어떻게 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 

OCaml의

이 두 클래스를 가지고 내가이 개 구체적인 클래스 collection['a] iterator_queue iterator의 하위 유형의 ['a] queue 하위 유형을 작성해야합니다.

주로 두 가지 유형이 연결될 수있는 방법이 없기 때문에 iterator : unit -> 'a iterator 메서드를 정의하는 방법을 알고 싶습니다. ['a] iterator_queue은 추상적 인 것들로부터 상속되어야합니까? 또는 다르게 진행해야합니까?

답변

4

아마도 가장 쉬운 방법은 큐의 정의 범위 내에서 반복기를 객체로 정의하는 것입니다 (자바에서는 "내부 클래스"라고합니다). 예를 들어

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 (불변의) 값에 대한 참조이다. 큐에 대한 후속 변경 사항은] 복기에] 영되지 않습니다.

+1

내가 생각한 방식 중 하나는 시험을 거쳐야하는 데, 해결책을 찾기 위해 노력하고 있습니다.) – 0xFF

1

이것이 단순히 재귀 클래스 정의의 테스트일지도 모른다고 생각됩니다.

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