(* Part I *) let rec fact (n:nat) : nat = if n <= 0 then 1 else fact (n-1) * n ;; type cont = nat -> nat ;; let rec fact_cont (n:nat) (k:cont) : nat = if n <= 0 then k 1 else fact_cont (n-1) (fun m -> k (m*n)) ;; Lemma 1: For all natural numbers n, for all k:cont, fact_cont n k == k (fact n) Proof: By induction on the natural n. case n = 0 pick an arbitrary continuation k: fact_cont 0 k == k 1 (eval) == k (fact 0) (eval, reverse) case n = i+1 (for some natural number i) IH: for all k:cont, fact_cont i k == k (fact i) Must prove: for all k:cont, fact_cont (i+1) k == k (fact (i+1)) proof: pick an arbitrary continuation k: fact_cont (i+1) k == if i+1 <= 0 then k 1 else fact_cont (i+1-1) (fun m -> k (m*(i+1))) (eval) == fact_cont (i+1-1) (fun m -> k (m*(i+1))) (eval) == fact_cont i (fun m -> k (m*(i+1))) (math) == (fun m -> k (m*(i+1))) (fact i) (IH) == k ((fact i)*(i+1)) (eval, fact valuable) == k ((fact ((i+1)-1))*(i+1)) (math) == k (if i+1 <= 0 then 1 else fact ((i+1)-1) * (i+1)) (eval, reverse, and i+1 > 0 since i is a natural number) == k (fact (i+1)) (eval, reverse) QED Theorem 2: For all natural numbers n, fact_cont n (fun m -> m) == fact n Proof: By equational reasoning. fact_cont n (fun m -> m) == (fun m -> m) (fact n) (by lemma 1, instantiating k with (fun m -> m)) == fact n (eval, since fact n valuable since fact total) QED (* Part III *) type tree = Leaf | Node of int * tree * tree;; let rec inc (t:tree) (a:int) : tree = match t with Leaf -> Leaf | Node(i,left,right) -> Node(i+a, inc left a, inc right a) ;; Theorem 3: for all t:tree, inc (inc t a) b == inc t (a+b) Proof: By induction on the structure of trees t. case t = Leaf inc (inc Leaf a) b == inc (match Leaf with Leaf -> Leaf | Node (i,left,right) -> ...) b (eval) == inc Leaf b (eval) == (match Leaf with Leaf -> Leaf | Node (i,left,right) -> ...) (eval) == Leaf (eval) == (match Leaf with Leaf -> Leaf | Node (i,left,right) -> ...) (eval, reverse) == inc Leaf (a+b) (eval, reverse) case t = Node(i,left,right) IH1: inc (inc left a) b == inc left (a+b) IH2: inc (inc right a) b == inc right (a+b) inc (inc (Node(i,left,right)) a) b == inc (Node(i+a,inc left a, inc right a)) b (eval 2 steps) == Node(i+a+b,inc (inc left a) b, inc (inc right a) b) (eval 2 steps, since +, inc total Node(i+a,...) valuable) == Node(i+a+b, inc left (a+b), inc right (a+b)) (IH1 and IH2) == Node(i+(a+b), inc left (a+b), inc right (a+b)) (associativity of +) == inc (Node(i,left,right)) (a+b) (eval, reverse, 2 steps) QED