Created
April 15, 2013 14:47
-
-
Save cohama/5388644 to your computer and use it in GitHub Desktop.
functor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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