OCaml理解函子与更复杂的例子

OCaml理解函子与更复杂的例子,ocaml,Ocaml,这是我的函子ORDTYPE。我想在EmptyQueue中使用compare。 我不知道如何注入函子。每次我收到错误,我都有无效的签名。 我试图在struct之前声明functor(Key:ORDTYPE)->,但它错了。 我不理解函子的概念。我在ocamlwiki中看到了一些简单的例子,但我不知道如何处理更复杂的事情 简而言之,我想在emptyqueue中使用comparator。但我不知道如何处理这个问题,让它变得更抽象 module type ORDTYPE = sig type t

这是我的函子ORDTYPE。我想在EmptyQueue中使用compare。 我不知道如何注入函子。每次我收到错误,我都有无效的签名。 我试图在struct之前声明functor(Key:ORDTYPE)->,但它错了。 我不理解函子的概念。我在ocamlwiki中看到了一些简单的例子,但我不知道如何处理更复杂的事情

简而言之,我想在emptyqueue中使用comparator。但我不知道如何处理这个问题,让它变得更抽象

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

module Icmp:ORDTYPE with type t= int=
struct
    type t = int
    let compare = fun x y -> if( x< y) then 0 else 1
end;;


module type STH=
sig
  type priority
  type 'a t
  val comp: x -> x->bool
end;;


module Emptyqueue (Comp: ORDTYPE): STH with type priority= int =
    struct
        type priority = int
        type 'a t = Empty 
        let comp = fun x y -> Comp.comp x y

    end;;
模块类型或类型=
信号
t型
val比较:t->t->int
完;;;
模块Icmp:ORDTYPE,类型t=int=
结构
类型t=int
让我们比较=乐趣x y->如果(xx->bool
完;;;
模块Emptyqueue(Comp:ORDTYPE):类型优先级为int的STH=
结构
类型优先级=int
输入'a t=Empty
让comp=fun x y->comp.comp x y
完;;;

我编辑了我认为我应该怎么做,但它没有。工作。

你错过的是需要在签名
STH
中定义
x
。我将使用更清晰的名称
elt
,而不是
x
。一旦
STH
具有
elt
,我们也可以将其添加到
Emptyqueue
中,或者使用“破坏性替换”,即签名修改语法
与…:=

请注意我在“校正”示例中介绍的差异,因为您有一些不匹配的地方需要纠正

module type ORDTYPE =
sig
  type t
  val compare : t -> t -> int
end;;
module Icmp:ORDTYPE with type t= int=
struct
  type t = int
  let compare = fun x y -> if( x< y) then 0 else 1
end;;
module type STH=
sig
  type priority
  type 'a t
  type elt
  val comp: elt -> elt -> bool
end;;
module Emptyqueue (Comp: ORDTYPE):
  (STH with type priority= int and type elt := Comp.t) =
struct
  type priority = int
  type 'a t = Empty 
  let comp = fun x y -> Comp.compare x y > 0
end;;
模块类型或类型=
信号
t型
val比较:t->t->int
完;;;
模块Icmp:ORDTYPE,类型t=int=
结构
类型t=int
让我们比较=乐趣x y->如果(xelt->bool
完;;;
模块清空队列(组件:ORDTYPE):
(类型优先级为int,类型elt为Comp.t的某事物)=
结构
类型优先级=int
输入'a t=Empty
让comp=fun x y->comp.comp比较x y>0
完;;;