; CS389R Fall, 2011 Recursion and Induction October 20, 2011 ; Use your own paper. Remember to put your name on your answers. There are ; two problems, each worth 50 points. Partial credit will be given. Please ; write clearly. ; Problem 1 (50 points): ; Define the function RPL that replaces each occurrence of e as an element in a ; list x by the position of that occurrence in x. ; Ex: (RPL 'E '(A B E C E D E E F)) ; = ; '(A B 2 C 4 D 6 7 F) ; Answer: (defun rpl1 (e x i) (cond ((endp x) nil) ((equal e (car x)) (cons i (rpl1 e (cdr x) (+ 1 i)))) (t (cons (car x) (rpl1 e (cdr x) (+ 1 i)))))) (defun rpl (e x) (rpl1 e x 0)) (defthm example-rpl (equal (RPL 'E '(A B E C E D E E F)) '(A B 2 C 4 D 6 7 F)) :rule-classes nil) ; Alternative Answer: (defun alt-rpl1 (e x len) (cond ((endp x) nil) ((equal e (car x)) (cons (- len (len x)) (alt-rpl1 e (cdr x) len))) (t (cons (car x) (alt-rpl1 e (cdr x) len))))) (defun alt-rpl (e x) (alt-rpl1 e x (len x))) (defthm rpl1-is-alt-rpl1 (implies (natp i) (equal (rpl1 e x i) (alt-rpl1 e x (+ i (len x)))))) (defthm rpl-is-alt-rpl (equal (rpl e x) (alt-rpl e x))) ; Problem 2 (50 points): Given the following definitions: (defun dn (n) ; E.g., (dn 5) = (5 4 3 2 1) (if (zp n) nil (cons n (dn (- n 1))))) (defun up (n a) ; E.g., (up 5 nil) is (1 2 3 4 5) (if (zp n) a (up (- n 1) (cons n a)))) (defun ap (x y) ; our familiar ap (if (endp x) y (cons (car x)(ap (cdr x) y)))) (defun rv (x) ; our familiar rev but with a shorter name (if (endp x) nil (ap (rv (cdr x)) (list (car x))))) ; And given these two theorems which you may assume: (defthm ap-assoc (equal (ap (ap a b) c) (ap a (ap b c)))) (defthm ap-rv-nil (equal (ap (rv x) nil) (rv x))) ; Prove that (up n nil) is the reverse of (dn n). ; Answer: (defthm lemma (equal (up n a) (ap (rv (dn n)) a))) (defthm main (equal (up n nil) (rv (dn n)))) ; The End