# lec09 - (* Set data abstraction, with union and...

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

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: (* Set data abstraction, with union and intersection * introduced in lecture 7 * 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) * mem x (inter S1 S2)=(mem x S1 )&amp;&amp; (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 -&gt; 'a set -&gt; 'a set val mem : 'a -&gt; 'a set -&gt; bool val rem : 'a -&gt; 'a set -&gt; 'a set val size: 'a set -&gt; int val union: 'a set -&gt; 'a set -&gt; 'a set val inter: 'a set -&gt; 'a set -&gt; 'a set end e module Set : SETSIG = struct (* Simple implementation of sets as lists without duplicates * Abstraction function: the list [a1;...;an] represents the * set {a1;...;an}. represents the empty set, {}. * * Representation invariant: the list contains no duplicate * elements. *) type 'a set = 'a list let empty = let repOK l = List.fold_left (fun a x -&gt; if List.mem x a then raise (Failure &quot;Invalid set, contains duplicates&quot;) else x::a) l let add x l = repOK (if List.mem x (repOK l) then l else x :: l) let mem x l = List.mem x (repOK l) let rem x l = repOK (List.filter (fun h -&gt; h&lt;&gt;x) (repOK l)) let size l = List.length (repOK l) let union l1 l2 = repOK (List.fold_left (fun a x -&gt; if List.mem x l2 then a else x::a) (repOK l2) (repOK l1)) let inter l1 l2 = repOK (List.filter (fun h -&gt; List.mem h l2) (repOK l1)) end e (* Polynomial abstract data type. *) ( module type POLYNOMIAL = sig (* A poly is a univariate polynomial with integer * coefficients. For example, 2 + 3x + x^3. *) type poly (* zero is the polynomial 0 *) val zero: poly (* singleton(c,d) is the polynomial cx^d....
View Full Document

## This note was uploaded on 10/25/2009 for the course PHYS 2214 at Cornell University (Engineering School).

### Page1 / 5

lec09 - (* Set data abstraction, with union and...

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

View Full Document
Ask a homework question - tutors are online