Yaw*_*war 6 ocaml subtyping polymorphic-variants
我有以下代码:
module Test : sig
type +'a t
val make : int -> [< `a | `b] t
end = struct
type 'a t = Foo of int | Bar of string
let make = function
| 0 -> (Foo 0 : [`a] t)
| _ -> (Bar "hi" : [`a] t)
end
Run Code Online (Sandbox Code Playgroud)
您可能会注意到,抽象类型'a t在其类型参数中被声明为协变'a,并且make构造函数被声明为返回多态变体case 或的子类型.ab
在我的实现中make,返回子类型[a] t仍应遵循协方差规则,因为子类型在返回类型位置.
但是,我收到以下错误:
Error: Signature mismatch:
...
Values do not match:
val make : int -> [ `a ] t
is not included in
val make : int -> [< `a | `b ] t
File ".../cov.ml", line 3, characters 3-34:
Expected declaration
File ".../cov.ml", line 7, characters 7-11:
Actual declaration
Run Code Online (Sandbox Code Playgroud)
关于如何说服OCaml该make函数真正返回有效子类型的任何建议[a | b] t?
我做了一些实验:
# type 'a t = Foo of int | Bar of string;;
type 'a t = Foo of int | Bar of string
# let make = function
| 0 -> (Foo 0 : [`a] t)
| _ -> (Bar "hi" : [`a] t);;
val make : int -> [ `a ] t = <fun>
# (make : int -> [< `a | `b] t);;
- : int -> [ `a ] t = <fun>
# let make2 : int -> [< `a | `b] t = make;;
val make2 : int -> [ `a ] t = <fun>
# let make3 = (make :> int -> [< `a | `b] t);;
val make3 : int -> [< `a | `b ] t = <fun>
Run Code Online (Sandbox Code Playgroud)
因此,显然 OCaml 确实识别了超类型关系,但仍然更喜欢坚持更精确的子类型,除非进行强制。其他人可能知道类型理论的原因。但正如你的问题只是
[...]如何说服 OCaml [...]
我的答案是:像这样使用强制
module Test : sig
type +'a t
val make : int -> [< `a | `b] t
end = struct
type 'a t = Foo of int | Bar of string
let make = (function
| 0 -> (Foo 0 : [`a] t)
| _ -> (Bar "hi" : [`a] t)
:> int -> [< `a | `b] t)
end
Run Code Online (Sandbox Code Playgroud)