Hi, I’m newbie to type abstraction using OCaml module. I’ve just read “Functors” part in manual. I’m implementing AbstractSet that takes any type which has order, based on sorted list. (similar to the example of that documents)
However, when doing this together with separating compile unit, I stuck at some point. I think showing my code is more straightforward that summarizing it. (Since I’m not used to the terminologies related to this topic)
OrderedTypes.ml: (It’s almost same with the manual)
type comparison = Less | Equal | Greater
module type ORDERED_TYPE =
sig
type t
val compare: t -> t -> comparison
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;;
Set.ml: Set based on sorted list
module type SET =
functor (Elt: ORDERED_TYPE) ->
sig
type element
type set
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end
module AbstractSet_L =
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
main.ml: simple test code using my set
open OrderedTypes
open Set
module StringSet = AbstractSet_L(OrderedString);;
let string_set_ex = StringSet.empty in
let string_set_ex = StringSet.add "hi" string_set_ex in
Printf.printf "%B" StringSet.member "hi" string_set_ex;
When I compile these with following commands,
ocamlc -c OrderedTypes.ml
ocamlc -c Set.ml
ocamlc -c main.ml
the error occurs in main.ml
at the point StringSet.add "hi" string_set_ex
8 | let string_set_ex = StringSet.add "hi" string_set_ex in
^^^^
Error: This expression has type string but an expression was expected of type
OrderedTypes.OrderedString.t
I understood that this is because of type abstraction of the element
of Set, which my functor SET
produces. The mentioned manual also deals with this issue in 40p, but my situation is slightly different. The document is using restriction on pre-defined SET
signature with with type element = Elt.t
phrase. I don’t know how to apply this style to my code, with my SET
functor producing the anonymous signature.
I’ve tried to add with type element = Elt.t
to SET
like follows, but the error on main.ml
still remains
module type SET =
functor (Elt: ORDERED_TYPE) ->
(sig
type element
type set
val empty : set
val add : element -> set -> set
val member : element -> set -> bool
end with type element = Elt.t)