CS 565 Programming Languages
Midterm, Mar 25, 2002
Solution

Question 1
----------
E has the principal type:  [(int -> t) -> (t -> s)] -> [int -> t] -> s.


Question 2
----------
Answer:  no.
Justification: draw the types as automata, construct the product automaton, and
observe that the path 1011 leads to an accepting state of the form (->,top,1).


Question 3
----------
(define f
  (lambda (n)
    (if (< n 100)
        n
        (+ 2 (f (f (- n 8)))))))


;; CPS:
            
(define f-cps-main
  (lambda (n)
    (f-cps n (lambda (v) v))))

(define f-cps
  (lambda (n k)
    (if (< n 100)
        (k n)
        (f-cps (- n 8) (lambda (v) (f-cps v (lambda (w) (k (+ 2 w)))))))))


;; First-order form:

;;    Represent (lambda (v) v)) 
;;           as (),
;;          and (lambda (v) (f-cps v (lambda (w) (k (+ 2 w)))))
;;           as (cons 1 k) where 1 is a tag
;;          and (lambda (w) (k (+ 2 w)))
;;           as (cons 2 k) where 2 is a tag

(define f-fo-main
  (lambda (n)
    (f-fo n '())))

(define f-fo
  (lambda (n k)
    (if (< n 100)
        (apply-cont-fo k n)
        (f-fo (- n 8) (cons 1 k)))))

(define apply-cont-fo
  (lambda (k x)
    (if (null? k)
        x
        (case (car k)
              ((1) (f-fo x (cons 2 (cdr k))))
              ((2) (apply-cont-fo (cdr k) (+ 2 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 100)
        (begin
         (set! x n)
         (apply-cont-imp))
        (begin
         (set! n (- n 8))
         (set! k (cons 1 k))
         (f-imp)))))

(define apply-cont-imp
  (lambda ()
    (if (null? k)
        x
        (case (car k)
              ((1) (begin
                     (set! n x) 
                     (set! k (cons 2 (cdr k)))
                     (f-imp)))
              ((2) (begin
                     (set! k (cdr k))
                     (set! x (+ 2 x))
                     (apply-cont-imp)))))))

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].
