lec07 - (* Code for lectures 7 and 8, Spring 2009 *) (* Set...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
(* Code for lectures 7 and 8, Spring 2009 *) ( (* Set data abstraction, with union and intersection * mem x empty = false * mem x (add x S)=true * mem x (rem x S)=false * mem x (union S1 S2)=(mem x S1) || (mem x S2) * size empty = 0 * size (add x S) = if mem x S then (size S) else (size S)+1 * size (rem x S) = if mem x S then (size S)-1 else (size S) *) module type SETSIG = sig type 'a set val empty : 'a set val add : 'a -> 'a set -> 'a set val mem : 'a -> 'a set -> bool val rem : 'a -> 'a set -> 'a set val size: 'a set -> int val union: 'a set -> 'a set -> 'a set val inter: 'a set -> 'a set -> 'a set end e (* Simple implementation of sets as lists with duplicates *) ( module Set : SETSIG = struct type 'a set = 'a list let empty = [] let add x l = x :: l let mem x l = List.mem x l let rem x l = List.filter (fun h -> h<>x) l let rec size l = match l with [] -> 0 | h::t -> size(t) + (if List.mem h t then 0 else 1) let union l1 l2 = l1 @ l2 let inter l1 l2 = List.filter (fun h -> List.mem h l2) l1 end e (* Test cases, using assertion *) ( let ts = Set.add 1 Set.empty;; assert (Set.mem 1 ts);; let ts = Set.add 1 ts;; assert (Set.mem 1 ts);; let ts = Set.add 2 ts;; assert ((Set.mem 1 ts) & (Set.mem 2 ts));; assert ((Set.size ts)=2);; let ts = Set.rem 1 ts;;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 10/25/2009 for the course PHYS 2214 at Cornell.

Page1 / 4

lec07 - (* Code for lectures 7 and 8, Spring 2009 *) (* Set...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online