; Functions for 2019 CS340d class, Lab 2 supplement ; For your automatic tree-allocation routines (implemented for Lab 2), ; implement these functions. See the end for a diagram of an ; association list. Note, when reading input, Lisp ``up cases'' all ; symbols, so all Lisp code shown below should be thought of as being ; in uppercase characters (except comments). (defun app (x y) ;; Appends list x to list y (declare (xargs :guard t)) (if (ATOM x) y (CONS (CAR x) (app (CDR x) y)))) (defun rev (x) ;; Reverses list x (declare (xargs :guard t)) (if (ATOM x) NIL (app (rev (CDR x)) (CONS (CAR x) NIL)))) (defun cons-copy (x) ;; Duplicates tree x (declare (xargs :guard t)) (if (ATOM x) x (CONS (cons-copy (CAR x)) (cons-copy (CDR x))))) (defun cons-count (x) ;; Counts number of CONS pairs in tree x (declare (xargs :guard t)) (if (ATOM x) 0 (+ 1 (cons-count (CAR x)) (cons-count (CDR x))))) (defun make-lst (n) ;; Makes a right-associated list of length n (declare (xargs :guard (natp n))) (if (zp n) NIL (CONS NIL (make-lst (- n 1))))) (defun make-tree (n) ;; Makes a full, binary tree of height n (declare (xargs :guard (natp n))) (if (ZP n) NIL (let ((rest (make-tree (- n 1)))) (CONS rest rest)))) (defun alstp (a) ;; Checkes whether a is a list of key-value pairs (declare (xargs :guard t)) (if (ATOM a) (null a) (and (CONSP (CAR a)) (alstp (CDR a))))) (defun mem (k a) ;; Given key k, search for and return (CONS k ) (declare (xargs :guard (alstp a))) (if (ATOM a) NIL (let* ((pair (CAR a)) (key (CAR pair))) (if (EQUAL k key) pair (mem k (CDR a)))))) (defun remove-k (k a) ;; Remove all key-value pairs with key k (declare (xargs :guard (alstp a))) (if (ATOM a) NIL (let* ((pair (CAR a)) (key (CAR pair))) (if (EQUAL k key) (remove-k k (CDR a)) (CONS pair (remove-k k (CDR a))))))) (defun replace-kv (k v a) ;; Add a new key-value pair (CONS k v) to the association list a ;; with all (CONS k ) pairs having been eliminated. (declare (xargs :guard (alstp a))) (CONS (CONS k v) (remove-k k a))) ; Below is an association list with three key-value pairs. (list (cons 'a 3) (cons 'b 4) (cons 'c 5)) ; Fully expanded, the above form is: (cons (cons 'a 3) (cons (cons 'b 4) (cons (cons 'c 5) NIL))) ; The next expression should return T. (alstp (cons (cons 'a 3) (cons (cons 'b 4) (cons (cons 'c 5) NIL)))) ; To access a member of our association list, use MEM: (mem 'c (cons (cons 'a 3) (cons (cons 'b 4) (cons (cons 'c 5) NIL)))) ; should evaluate to: (cons 'c 5) ; Pictorially, one might diagram the association list (above) as: ; O ; / \ ; O \ ; / \ \ ; a 3 \ ; O ; / \ ; O \ ; / \ \ ; b 4 \ ; O ; / \ ; O \ ; / \ \ ; c 5 \ ; NIL