0

原因机器学习

module type T = {
  type t('a); // Does not work
  type b; // Works
};

module A: T = {
  type t('a) = {.. b: bool} as 'a;
  type b = bool;
};
module B: T = {
  type t('a) = {.. c: int} as 'a;
  type b = int;
};

奥卡姆

module type T  = sig
  type 'a t /* Doesn't work */
  type b /* Works */
end
module A : T = struct type 'a t = < b :bool  ;.. > as 'a
                      type b = bool end 
module B : T = struct type 'a t = < c :int  ;.. > as 'a
                      type b = int end  

如何定义模块类型 A t('a) 使其抽象但与实现中的开放多态对象类型兼容?

4

2 回答 2

1

目前尚不清楚它是否真的有用,但您需要在模块类型中显式添加约束:

module type TA  = sig
  type 'a t constraint 'a = < b:bool; .. >
end
module A : TA = struct
  type 'a t = < b :bool  ;.. > as 'a
end
于 2021-05-22T10:45:51.510 回答
1

类型<b : bool; .. ><c : int; ..>不兼容很像int并且bool不兼容。换句话说,如果我们将行多态性放在一边,并专注于简单的类型构造函数,那么您正在尝试定义一个与类型匹配的接口,intbool不是其他任何东西,也就是有界多态性

理解子类型化不是继承也很重要。在您的情况下,您有两类b对象,具有方法的 -class 对象b

class virtual b = object
  method virtual b : bool
end

c具有方法的对象的类c


class virtual c = object
  method virtual c : int
end

我们可以定义一个bc具有这两种方法的对象类,自然地通过继承,

class virtual bc = object
  inherit b
  inherit c
end

现在,让我们煮一些东西来玩,

let b : b = object method b = true end
let c : c = object method c = 42 end
let bc : bc = object
  method b = false
  method c = 56
end

我们可以看到,尽管bc类类型被定义为从 b 和 c 继承,但我们不能强制b转换为c,

# (b : b :> bc);;
Line 1, characters 0-13:
1 | (b : b :> bc);;
    ^^^^^^^^^^^^^
Error: Type b = < b : bool > is not a subtype of bc = < b : bool; c : int > 
       The first object type has no method c

这是非常有意义的,因为我们试图将基类的对象向下转换为派生类的对象,这是一种非法操作。因此,当您具有按继承排序的类类型层次结构时,基类是超类型,派生类是子类型。例如,如果从thenv继承是 的子类型,uvu

v inherits-from u
-----------------
   u :> v

一旦你清楚地理解了这一点,你就可以设计一个合适的界面。

于 2021-05-24T13:34:10.703 回答