Ocaml的玩家

nlu*_*oni 12 ocaml functional-programming functor

我对仿函数有一点问题(它是结果类型).下面,我有一个使用Ordered类型的Set仿函数.我实际使用的set.ml自带的OCaml的一些指导,但我似乎做的一切ahhem权.我创建了一个带有整数的Ordered模块,并将其应用于Set仿函数,以获取此代码示例IntSet的最后一个模块.

当我尝试插入一个整数时,下一行失败了.我收到以下类型错误:

Error: This expression has type int but is here used with type
         SetInt.elt = Set(OrdInt).elt
Run Code Online (Sandbox Code Playgroud)

别误会我的意思,这里的类型系统是正确的.顶级报告的类型SetInt.eltSet(OrdInt).elt,但是当我使用ocaml提供的相同操作设置Set时,'same'行是,SetInt.elt = OrderedInt.t.好像我应该得到SetInt.elt = Ordered.t.

这很简单,我可能只是错过了一些愚蠢的细节!哎呀!

请注意:我已经简化了成员/插入函数,因为这个问题与类型有关.

module type Ordered =
  sig
    type t 
    val lt : t -> t -> bool
    val eq : t -> t -> bool
    val leq : t -> t -> bool
  end

module type S =
  sig
    type elt
    type t
    exception Already_Exists
    val empty  : t
    val insert : elt -> t -> t
    val member : elt -> t -> bool
  end

module Set (Elt:Ordered) : S = 
  struct
    type elt = Elt.t
    type t = Leaf | Node of t * elt * t
    exception Already_Exists
    let empty = Leaf
    let insert e t = t
    let member e t = false
  end

module OrdInt : Ordered =
  struct
    type t = int
    let lt a b = a < b
    let eq a b = a = b
    let leq a b = a <= b
  end

module IntSet = Set (OrdInt)

(* line that fails *)
let one_elm = IntSet.insert 1 IntSet.empty
Run Code Online (Sandbox Code Playgroud)

Tra*_*Man 15

你需要改变这两行

module Set (Elt:Ordered) : S = 
module OrdInt : Ordered =
Run Code Online (Sandbox Code Playgroud)

module Set (Elt:Ordered) : S with type elt = Elt.t = 
module OrdInt : Ordered with type t = int =
Run Code Online (Sandbox Code Playgroud)

没有这些,模块将没有将类型elt和t暴露为int的签名.

[编辑]:set.ml没有'with'位,因为有一个sml.mli,它声明了仿函数的签名,它确实有'with'.此外,如果您没有为其明确指定签名,OrdInt不需要'with',如下所示:

module OrdInt =
Run Code Online (Sandbox Code Playgroud)

您还可以通过定义模块来构造集合:

module IntSet = Set (struct
 type t = int
 let lt a b = a < b
 let eq a b = a = b
 let leq a b = a <= b
end) 
Run Code Online (Sandbox Code Playgroud)