类方法的可见细化

时间:2014-09-05 10:02:32

标签: class inheritance ocaml redeclaration

考虑以下小型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 *)

我想要实现的是优化x w.r.t的class z字段。 class y并且在z的类型中具有可见的细化,即

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

我想要实现的目标。

我非常有信心有一种方法可以让类型检查器能够说服改进的兼容性,但是如何?

1 个答案:

答案 0 :(得分:3)

看起来很难直接执行此操作:如果您尝试使用类型参数放宽method xy的类型,

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

您可以看到类型检查器强制'a 完全 x而不是#x的任何子类型x

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

因此将排除任何尝试用另一种类型重新定义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)