我有以下代码:
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正如您可能注意到的,抽象类型'a t在其类型参数'a中声明为协变量,而make构造函数被声明为返回多态变体案例a或b的子类型。
在我的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关于如何使OCaml确信make函数确实正在返回有效的[a | b] t子类型的建议
发布于 2018-01-13 13:14:35
我做了一些实验:
# 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>因此,显然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)
endhttps://stackoverflow.com/questions/48237453
复制相似问题