【发布时间】:2018-06-03 20:34:36
【问题描述】:
我对 Ocaml 中的模块类型感到困惑。
我想知道在什么情况下我们应该使用模块类型?
我通常使用 .mli 中的模块 sig 来暴露一些细节,然后把 .ml中对应的实现模块struct。
例如:
.mli
module A:
sig
type t = T of string
end
.ml
module A =
struct
type t = T of string
end
因此,我认为 Ocaml 的模块类似于 C 中的 .h 和 .c 文件。
我知道模块类型可以声明一个接口,但是这个接口不和Java的接口一样。
就像书中的一个例子:
open Core.Std
module type ID = sig
type t
val of_string : string -> t
val to_string : t -> string
end
module String_id = struct
type t = string
let of_string x = x
let to_string x = x
end
module Username : ID = String_id
module Hostname : ID = String_id
type session_info = { user: Username.t;
host: Hostname.t;
when_started: Time.t;
}
let sessions_have_same_user s1 s2 =
s1.user = s2.host
上述代码有一个错误:它将一个会话中的用户名与另一个会话中的主机进行比较,而这两种情况下都应该比较用户名。
模块类型似乎无法为其实现提供新的通用超类型。
模块类型的真正应用是什么?
【问题讨论】:
标签: types functional-programming ocaml