zel*_*ell 3 ocaml module include
任何人都可以帮我练习Jason Hickey的书吗?
基本上,问题是如何在实践中避免由于"包含"引起的以下冲突问题?谢谢.
# module type XSig = sig
type t
val x : t
end;;
# module A : XSig = struct
type t = int
let x = 0
end;;
# module B : XSig = struct
type t = int
let x = 1
end;;
# module C = struct
include A
include B
end;;
Run Code Online (Sandbox Code Playgroud)
我不知道究竟是什么问题,但是对于你的代码片段,有各种截然不同的方式来解释你想要做的事情.
你目前正在做的是密封A
并B
在两个抽象的,不兼容的签名下,然后尝试将它们混合在一个模块中,只是为了产生名称冲突.
也许你只是想避免名称冲突.最简单的解决方案,当然,是不使用相同的名称为两种类型的A.t
和B.t
.然后你可以"不包括B
":
module C = struct
include A
let x_b = B.x
end
Run Code Online (Sandbox Code Playgroud)
更好的解决方案是使用OCaml 3.12破坏性替换签名with type t := foo
,以掩盖t
模块中的类型B
:
module C = struct
include A
type u = B.t (* rename B.t into 'u' to avoid name conflict *)
include (B : XSig with type t := u) (* replaces 't' by 'u' *)
end
Run Code Online (Sandbox Code Playgroud)
您可能还需要模块的类型A
并且B
兼容.在这种情况下,您不能用抽象类型密封它们.
module type XSig = sig
type t
val x : t
end
module A = struct
type t = int
let x = 0
end
(* if you want to check that A can be sealed by XSig, do it here,
outside the main declaration *)
let _ = (module A : XSig)
module B = struct
type t = int
let x = 1
end
module C = struct
include (A : XSig with type t := int)
include (B : XSig with type t := int)
end
(* module C : sig
val x = int
end *)
Run Code Online (Sandbox Code Playgroud)
在这个例子中这两种类型A.t
和B.t
由破坏性托换除去:=
.如果您希望模块C
具有类型t
,则可以编写以下任一项:
module C = struct
type t = int
include (A : XSig with type t := t)
include (B : XSig with type t := t)
end
Run Code Online (Sandbox Code Playgroud)
或者,使用非破坏性替换(更改类型定义而不是删除它):
module C = struct
include (A : XSig with type t = int)
include (B : XSig with type t := t)
end
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅破坏性替换type type t := ...
的手册页;有关比较的经典with type t = ...
结构,请参阅该页面.