Skip to content

Instantly share code, notes, and snippets.

@cohama
Created April 15, 2013 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cohama/5388644 to your computer and use it in GitHub Desktop.
Save cohama/5388644 to your computer and use it in GitHub Desktop.
functor
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]
| head::tail ->
match Elt.compare x head with
| Equal -> s (* x is already in s *)
| Less -> x::s (* x is smaller than all elements of s *)
| Greater -> head::add x tail
let rec member x s =
match s with
| [] -> false
| head::tail ->
match Elt.compare x head with
| Equal -> true (* x belongs to s *)
| Less -> false (* x is smaller than all elements of s *)
| Greater -> member x tail
end;;
module OrderedString =
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 ans = StringSet.member "bar" (StringSet.add "bar" StringSet.empty) in
if ans then print_string "true" else print_string "false"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment