函数已经实现的类型模块ocaml

时间:2018-05-28 14:20:01

标签: module ocaml

我有一个模块类型Order,它将在几个模块中实现。 功能比较将在模块中实现。

module type Order = 
sig
  type t
  val compare: t -> t -> int
end

我还要创建一个函数max:

max a b = if (compare a b > 0) then a else b

我想在我的模块Order中编写这个函数的定义(不只是声明),以避免在子模块中重写相同的定义。

我试过了:

val max a b = if (compare a b > 0) then a else b

let max a b = if (compare a b > 0) then a else b

但它不起作用

1 个答案:

答案 0 :(得分:3)

您无法在模块的签名中实现功能。 我认为您在OCaml中使用functors解决了您遇到的问题。

您可以查看以了解其工作原理的代码示例是Set的实现。

在你的情况下,它看起来像:
编辑:考虑到Richard Degenne,octachron和PatJ的贡献:

module type Order =
sig
  type t
  val compare: t -> t -> int
end

module type Util =
sig
  type t
  val compare: t -> t -> int
  val max: t -> t -> t
end

module Make(Ord: Order): Util with type t := Ord.t =
struct
  type t = Ord.t
  let compare = Ord.compare
  let max a b = if (Ord.compare a b > 0) then a else b
end

为了使用它,您可以:

(*You first define a module for the specific case of int*)
module IntOrder = struct
  type t = int
  let compare = compare
end

(*You use the new module to build the corresponding Util module*)
module IntUtil = Make(IntOrder)

(*You can now use the functions defined in Util as if it was any other module*)
let x = IntUtil.max 1 2
let y = IntUtil.compare 1 2

(*But if you try to call it with the wrong type you get an error*)
let z = IntUtil.compare 1.6 2.5