我是 OCaml 的新手,在理解模块类型如何工作方面有些困难。
module type I = sig
type t
end
module EQ (M : I) = struct
let equal (x : M.t) (y : M.t) = x = y
end
(* Explicitly type declaration *)
module A : I = struct
type t = string
end
module EStr1 = EQ (A)
(* Error: This expression has type string but an expression was expected of type
A.t *)
let _ = EStr1.equal "1" "0" |> string_of_bool |> print_endline
(* No type declaration *)
module B = struct
type t = string
end
module EStr2 = EQ (B)
(* OK. Outputs false *)
let _ = EStr2.equal "1" "0" |> string_of_bool |> print_endline
在上面的代码中,我声明了模块类型I
、具有显式模块类型声明的模块和没有模块类型声明的A
模块。是接收类型模块并返回带有方法的模块的函子。B
EQ
I
equal
带有模块的示例A
导致编译错误,而另一个示例则按我预期运行。这些示例之间的语义差异是什么?