Skip to content

Instantly share code, notes, and snippets.

@j2labs
Created June 18, 2012 18:10
Show Gist options
  • Save j2labs/2949770 to your computer and use it in GitHub Desktop.
Save j2labs/2949770 to your computer and use it in GitHub Desktop.
functoring
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 (* x is already in s *)
| Less -> x :: s (* x is smaller than all elements of 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 (* x belongs to s *)
| Less -> false (* x is smaller than all elements of s *)
| Greater -> member x tl
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);;
StringSet.member "bar" (StringSet.add "foo" StringSet.empty);;
module OrderedNumber =
struct
type t = int
let compare x y = if x = y then Equal else if x < y then Less else Greater
end;;
module NumberSet = Set(OrderedNumber);;
let x = NumberSet.add 4 NumberSet.empty;;
let y = NumberSet.add 7 x;;
let z = NumberSet.add 2 y;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment