(* for ML Lecture 4 *) (* Definition of the structure MultiSet *) module MultiSet = struct exception Empty_Set exception Not_Found type 'a set = Leaf | Node of 'a * 'a set * 'a set let empty = Leaf let rec add set elt = match set with Leaf -> Node(elt, Leaf, Leaf) | Node(e, left, right) -> if e < elt then Node(e, left, add right elt) else Node(e, add left elt, right) let rec remove_biggest = function Leaf -> raise Empty_Set | Node(v, left, Leaf) -> (v, left) | Node(v, left, right) -> let (m, t) = remove_biggest right in (m, Node(v, left, t)) let remove_top = function Leaf -> raise Empty_Set | Node(_, left, Leaf) -> left | Node(_, Leaf, right) -> right | Node(_, left, right) -> let (t, newl) = remove_biggest left in Node(t, newl, right) let rec remove set elt = match set with Leaf -> raise Not_Found | Node(top, left, right) as whole -> if top = elt then remove_top whole else if (elt < top) then Node(top, remove left elt, right) else Node(top, left, remove right elt) let rec member set elt = match set with Leaf -> false | Node(top, left, right) -> if top = elt then true else if (elt < top) then member left elt else member right elt end (* > module MultiSet : > sig > exception Empty_Set > exception Not_Found > type 'a set = Leaf | Node of 'a * 'a set * 'a set > val empty : 'a set > val add : 'a set -> 'a -> 'a set > val remove_biggest : 'a set -> 'a * 'a set > val remove_top : 'a set -> 'a set > val remove : 'a set -> 'a -> 'a set > val member : 'a set -> 'a -> bool > end *) (* Definition of the signature MULTISET *) module type MULTISET = sig type 'a set (* abstract : implementation is hidden *) val empty : 'a set val add : 'a set -> 'a -> 'a set val remove : 'a set -> 'a -> 'a set val member : 'a set -> 'a -> bool exception Not_Found end (* > module type MULTISET = > sig > type 'a set > val empty : 'a set > val add : 'a set -> 'a -> 'a set > val remove : 'a set -> 'a -> 'a set > val member : 'a set -> 'a -> bool > exception Not_Found > end *) (* Applying signature to structure *) module AbstractMultiSet = (MultiSet : MULTISET) (* > module AbstractMultiSet : MULTISET *) (* cf: apply signature at the definition time *) module type ExampleSig1 = sig val pub : unit -> int end module Example1 : ExampleSig1 = struct let pub () = 3 end module Example2 : sig val pub : unit -> int end = struct let pub () = 1 let hidden () = 2 end