代码之家  ›  专栏  ›  技术社区  ›  nlucaroni

Ocaml中的函子

  •  12
  • nlucaroni  · 技术社区  · 17 年前

    我对函子(以及它的结果类型)有点问题。下面,我有一个使用有序类型的集合函子。实际上我用的是 set.ml ocaml提供了一些指导,但我似乎在做所有的事情 啊哼 正当我创建了一个带整数的有序模块,并将其应用于Set functor,以获取此代码示例中的最后一个模块IntSet。

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

    别误会,这里的打字系统是正确的。顶层报告的类型为 SetInt.elt 是 Set(OrdInt).elt 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
    
    1 回复  |  直到 17 年前
        1
  •  15
  •   TrayMan    17 年前

    你需要改变这两行

    module Set (Elt:Ordered) : S = 
    module OrdInt : Ordered =
    

    module Set (Elt:Ordered) : S with type elt = Elt.t = 
    module OrdInt : Ordered with type t = int =
    

    如果没有这些,模块将不会有将类型elt和t公开为int的签名。

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

    module OrdInt =
    

    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)