(* 15-150, Fall 2026 *) (* Stephanie Balzer & Dilsun Kaynar *) (* Code for Lecture 6: Work and Span *) (************************************************************************) (* Recall from the previous lecture: *) datatype tree = Empty | Node of tree * int * tree val t1 : tree = Node(Empty, 1, Node(Empty, 2, Empty)) val t2 : tree = Node(Node(Empty, 3, Empty), 4, Empty) val t12 : tree = Node(t1, 5, t2) (* Here is the tree code mentioned on page 8 of today's pdf: *) (* sum : tree -> int REQUIRES: true ENSURES: sum(T) evaluates to the sum of all the integers in T. *) fun sum (Empty : tree) : int = 0 | sum (Node(l,x,r)) = (sum l) + (sum r) + x val 0 = sum(Empty) val 15 = sum(t12) (************************************************************************) (* Here is a preview of sorting (see page 10 of WorkAnalysis.pdf): *) (* SML contains the following predefined type: datatype order = LESS | EQUAL | GREATER *) (* compare : int * int -> order REQUIRES: true ENSURES: compare(x,y) ==> LESS if x EQUAL if x=y compare(x,y) ==> GREATER if x>y *) fun compare(x:int, y:int):order = if x int list REQUIRES: L is sorted ENSURES: ins(x, L) evaluates to a sorted permutation of x::L *) fun ins (x : int, [ ] : int list) : int list = [x] | ins (x, y::L) = (case compare(x, y) of GREATER => y::ins(x, L) | _ => x::y::L) (* isort : int list -> int list REQUIRES: true ENSURES: isort(L) evaluates to a sorted permutation of L *) fun isort ([ ] : int list) : int list = [ ] | isort (x::L) = ins (x, isort L) val [1,2,3,4] = isort[3,1,4,2] (* We will see more efficient sorting next time. *) (************************************************************************)