# lec3 - let fun count(from:int to:int = if from=to then[to...

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

(* CSE 341 - ML code for Lecture 3 - Spring 2008 *) ( (* lists and lists of pairs *) ( fun append (lst1 : int list, lst2 : int list) = if null lst1 then lst2 else hd(lst1) :: append(tl(lst1), lst2) fun countup (from : int, to : int) = if from = to then [to] (* list of one element, same as to::[] *) else from :: countup(from+1,to) fun sum_pair_list (lst : (int * int) list) = if null lst then 0 else #1 (hd(lst)) + #2 (hd(lst)) + sum_pair_list(tl(lst)) fun firsts (lst : (int * int) list) = if null lst then [] else (#1 (hd lst))::(firsts(tl lst)) fun seconds (lst : (int * int) list) = if null lst then [] else (#2 (hd lst))::(seconds(tl lst)) fun sum_list (lst : int list) = if null lst then 0 else hd(lst) + sum_list(tl(lst)) fun sum_pair_list2 (lst : (int * int) list) = (sum_list (firsts lst)) + (sum_list (seconds lst)) (* let-expressions *) fun f (z : int) = let val x = if z > 0 then z else 34 val y = x+9 in x+(let val q = y+2 in hd [q] end) end fun g() = let val x = 1 in (let val x = 2 in x+1 end) + (let val y = x+2 in y+1 end) end fun countup_from1 (x:int) =

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: let fun count (from:int, to:int) = if from=to then [to] else from :: count(from+1,to) in count(1,x) end fun countup_from1_better (x:int) = let fun count (from:int) = if from=x then [x] else from :: count(from+1) in count(1) end (* max, repeated computation, and options *) ( (* badly named: evaluates to 0 on empty list *) fun bad_max (lst : int list) = if null lst then 0 else if null (tl(lst)) then hd(lst) else if hd(lst) > bad_max(tl(lst)) then hd(lst) else bad_max(tl(lst)) (* badly named: evaluates to 0 on empty list *) fun good_max (lst : int list) = if null lst then 0 else if null (tl(lst)) then hd(lst) else (* for style, could also use a let-binding for hd(lst) *) let val tl_ans = good_max(tl(lst)) in if hd(lst) > tl_ans then hd(lst) else tl_ans end e fun better_max (lst : int list) = if null lst then NONE else let val tl_ans = better_max(tl(lst)) in if isSome tl_ans andalso valOf tl_ans > hd(lst) then tl_ans else SOME (hd(lst)) end...
View Full Document

## This note was uploaded on 10/12/2009 for the course CSE 341 taught by Professor Staff during the Spring '08 term at University of Washington.

### Page1 / 2

lec3 - let fun count(from:int to:int = if from=to then[to...

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

View Full Document
Ask a homework question - tutors are online