CS 565 Programming Languages Midterm, Apr 4, 2001 Solution Question 1 ---------- A run of Wand's algorithm: Triples: Constraints: -------- ------------ (empty, lambda (f) lambda (x) ((f x) (f 5)), t0) t0 = t1 -> t2 (f:t1, lambda (x) ((f x) (f 5)), t2) t2 = t3 -> t4 (f:t1,x:t3, (f x) (f 5), t4) (f:t1,x:t3, (f x), t5 -> t4) (f:t1,x:t3, (f 5), t5) (f:t1,x:t3, f, t6 -> (t5 -> t4)) t1 = t6 -> (t5 -> t4) (f:t1,x:t3, x, t6) t3 = t6 (f:t1,x:t3, f, t7 -> t5) t1 = t7 -> t5 (f:t1,x:t3, 5, t7) t3 = t7 t7 = int We have t1 = t6 -> (t5 -> t4) and t1 = t7 -> t5, so any solution must satisfy t5 = t5 -> t4, which is impossible. Conclusion: E does not have a simple type. Question 2 ---------- (define f (lambda (n) (if (< n 3) 2 (if (< 10 n) (f (- n 8)) (+ 3 (f (- n 1))))))) ;; CPS: (define f-cps-main (lambda (n) (f-cps n (lambda (v) v)))) (define f-cps (lambda (n k) (if (< n 3) (k 2) (if (< 10 n) (f-cps (- n 8) k) (f-cps (- n 1) (lambda (v) (k (+ 3 v)))))))) ;; First-order form: ;; Represent (lambda (v) v)) as (), ;; and (lambda (v) (k (+ 3 v))) as (cons 1 k), where 1 is a tag. (define f-fo-main (lambda (n) (f-fo n '()))) (define f-fo (lambda (n k) (if (< n 3) (apply-cont-fo k 2) (if (< 10 n) (f-fo (- n 8) k) (f-fo (- n 1) (cons 1 k)))))) (define apply-cont-fo (lambda (k x) (if (null? k) x (apply-cont-fo (cdr k) (+ 3 x))))) ;; Imperative form: ;; Just three global variables: n k x. (define n '*dummy) (define k '()) (define x '*dummy) (define f-imp-main (lambda () (f-imp))) (define f-imp (lambda () (if (< n 3) (begin (set! x 2) (apply-cont-imp)) (if (< 10 n) (begin (set! n (- n 8)) (f-imp)) (begin (set! n (- n 1)) (set! k (cons 1 k)) (f-imp)))))) (define apply-cont-imp (lambda () (if (null? k) x (begin (set! k (cdr k)) (set! x (+ 3 x)) (apply-cont-imp))))) Question 3 ---------- Answer: yes. Justification: draw the types as automata, construct the product automaton, and observe that no accepting states are reachable [a solution to the midterm should show the automata]. Question 4 ---------- Lemma 1 (Type Preservation) If |- e : t, and e -> e', then |- e' : t. Lemma 2 (Progress) If |- e : t, then e is not stuck. Theorem A well-typed expression cannot go wrong. Proof Let e be a well-typed expression, that is, suppose we have |- e : t. Suppose e can go wrong, that is, suppose e -> e_1 -> ... -> e_n, and en is stuck. By Lemma 1 (and induction), we have that |- e_n : t, and by Lemma 2 we then have that e_n is not stuck, a contradiction. Now, Lemma 1 and Lemma 2 can be proved by standard methods, see Lecture Note 3. I will skip the details here [a solution to the midterm should show some of the details].