下面的代码产生错误类型This expression has type float but an expression was expected of type ModuleA.t
,即使ModuleA.t
和float
是相同的,如在ModuleA
定义:
module type ModuleT =
sig
type t
val to_string : t -> string
end
module ModuleA : ModuleT =
struct
type t = float
let to_string x = string_of_float x
end
let () =
let x = 3.0 in
Printf.printf "%s\n" (ModuleA.to_string x)
如果我不定义模块类型ModuleT
,但只有ModuleA
,类型错误消失。我怎样才能解决这个类型的错误,同时保持模块类型定义?
问题是,你是隐藏在t
ModuleT
的定义,由于缺乏约束你的问题显而易见的解决方案是只完全定义它:
module type ModuleT =
sig
type t = float
val to_string : t -> string
end
但根据在首位定义ModuleT
的原因,这种解决方案可能不合适。例如,ModuleT
因为你已经定义它,你可以提供以下定义一个ModuleB
:
module ModuleB : ModuleT =
struct
type t = int
let to_string x = string_of_int x
let make : int -> t = fun n -> n
end
let () =
let x = 3 in
Printf.printf "%s\n" (ModuleB.to_string (ModuleB.make x))
如果t
ModuleT
被限制为float
你不能这样做,因为int
显然不会float
统一。