3

OCaml のファンクターに関する次のコードを取得しました。

type comparison = Less | Equal | Greater;;

module type ORDERED_TYPE =
    sig
        type t
        val compare: t -> t -> comparison
    end
;;

module Set =
    functor (Elt: ORDERED_TYPE) ->
        struct
            type element = Elt.t
            type set = element list
            let empty = []
            let rec add x s =
                match s with
                | [] -> [x]
                | hd :: tl ->
                    match Elt.compare x hd with
                    | Equal -> s
                    | Less -> x :: s
                    | Greater -> hd :: add x tl
            let rec member x s =
                match s with
                | [] -> false
                | hd :: tl ->
                    match Elt.compare x hd with
                    | Equal -> true
                    | Less -> false
                    | Greater -> member x tl
    end
;;

module OrderedString : ORDERED_TYPE = 
    struct
        type t = string
        let compare x y =
            if x = y then Equal
            else if x < y then Less
            else Greater
    end
;;

module StringSet = Set(OrderedString);;

let out = StringSet.member "foo" (StringSet.add "foo" StringSet.empty);; (*compile error, where "foo" is expected OrderedString.t but actually is string*)

上記のエラーは、: ORDERED_TYPEinを削除することで回避できますmodule OrderedString : ORDERED_TYPE =

理由がわかりません。

同様に、次のようなモジュールに型がある場合

module A = struct type t = string end;;

文字列値をタイプとして指定できますA.tが、実際の値は指定できませんstring

ありがとう。

4

2 に答える 2

2

Tomash が述べたように、型制約がありませんが、ファンクター シグネチャにはありません (実際にはコードには何もありません) が、それに与えている引数にはあります。書くときは基本的に

module OrderedString : ORDERED_TYPE = struct ... end

は署名の抽象型であるため、型tの定義はOrderedString抽象化されます。ここで必要なのは、それが確かに の実装であるが、型が既知であるということです。これはまさにあなたが得るものですtORDERED_TYPEOrderedStringORDERED_TYPEt

module OrderedString: ORDERED_TYPE with type t = string = struct ... end
于 2013-07-25T09:04:32.103 に答える