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_TYPE
inを削除することで回避できますmodule OrderedString : ORDERED_TYPE =
理由がわかりません。
同様に、次のようなモジュールに型がある場合
module A = struct type t = string end;;
文字列値をタイプとして指定できますA.t
が、実際の値は指定できませんstring
ありがとう。