2014-09-05 68 views
4

考慮以下小OCaml的類層次結構:類方法可見細化

class x = object method i = 0 end ;; 
class y = object method x = new x end ;; 
class x2 = object method i = 0 method j = 1 end ;; 
class z = object method x = new x2 inherit y end;; (* type error *) 

我想實現的是細化領域class z w.r.t.的xclass y並有細化可見在z的類型,即

class z = object method x = (new x2 :> x) inherit y end;; 
(new z)#x#j;; (* type error *) 

我想達到的目標。

我相當有信心,有一種方法來說服細化的兼容性的類型檢查,但如何?

回答

3

它看起來是很難直接做到這一點:如果你試圖使用一種類型的參數,以放鬆的method x類型的y

class ['a] y = object 
    constraint 'a = #x 
    method x = new x 
end 

,你可以看到類型檢查力量'a恰好x#xx的不屬於任何亞型:

class ['a] y = object 
    constraint 'a = x 
    method x = new x 
end 

這將因此precl ude任何企圖用另一種類型重新定義method x。但是,它可以定義一個期望#x類型的對象作爲參數的類,並從中導出原始class yclass z

class x = object method i = 0 end ;; 

class ['a] y_gen (x:'a) = object 
    constraint 'a = #x 
    method x = x end 
;; 

class y = object inherit [x] y_gen (new x) end 

class x2 = object method i = 0 method j = 1 end ;; 

class ['a] z_gen (x:'a) = object 
    constraint 'a = #x2 
    inherit ['a] y_gen x 
    method! x = x 
end;; 

class z = object inherit [x2] z_gen (new x2) end 

此外,z的確是y一個亞型,即,以下是正確類型檢查:

let my_z = new z 
let my_y = (my_z :> y)