;;; David Bindel, CS 164 ;;; Solutions to exercises posed in section ;; Substitute one jargon word for another (defun jargon-translate (list mappings) "Translate jargon words in a sentence" (mapcar #'(lambda (word) (or (cdr (assoc word mappings)) word)) list)) ;; Substitute one jargon phrase for another (defun match-start (seq1 seq2) "Tell whether seq1 matches the start of seq2" (or (null seq1) (and (eq (car seq1) (car seq2)) (match-start (cdr seq1) (cdr seq2))))) (defun jargon-translate-2 (list mappings) "Translate jargon phrases in a sentence" (when list (let* ((mapping (assoc-if #'(lambda (x) (match-start x list)) mappings)) (old-phrase (car mapping)) (new-phrase (cdr mapping)) (rest (nthcdr (length old-phrase) list))) (if mapping (append new-phrase (jargon-translate-2 rest mappings)) (cons (car list) (jargon-translate-2 (cdr list) mappings)))))) ;; Play "Mad Libs" with a list (defun choose-random (list) "Choose a list element at random." (nth (random (length list)) list)) (defun mad-lisp (list mappings) "Fill in a Mad Libs template" (mapcar #'(lambda (word) (let ((map (assoc word mappings))) (if map (choose-random (cdr map)) word))) list)) ;; Find clusters of identical codes (defun cluster-programs (codes) "Find programmers who have the same codes." (let ((ht (make-hash-table :test #'equal)) (groups nil)) (dolist (code codes) (push (car code) (gethash (cdr code) ht))) (maphash #'(lambda (key val) (push val groups)) ht) groups)) ;;; --- Test cases for above codes --- ;; Try the jargon word translator (setf *jargon-mappings* '((code . product) (bugs . features) (confusing . powerful))) (setf *my-sentence* `(this code is confusing and has many bugs)) (print (jargon-translate *my-sentence* *jargon-mappings*)) ;; Try the Mad Lisp program (setf *madlib-mappings* `((noun frog log dog rat hat mat) (verb eat throw write code) (adj lazy industrious novice expert) (adv violently peacefully unoriginally))) (setf *my-sentence* `(the adj noun decided to adv verb the noun)) (print (mad-lisp *my-sentence* *madlib-mappings*)) ;; Try the jargon phrase rewriter (setf *jargon-phrases* '(((fix bugs) . (enable customer satisfaction)) ((buggy programs) . (correctness impaired software)) ((hate) . (feel strong aversion toward)) ((programmers) . (software engineering specialists)))) (setf *my-sentence-2* '(programmers fix bugs and hate buggy programs)) (print (jargon-translate-2 *my-sentence-2* *jargon-phrases*)) ;; Try the code clustering program (setf *codes* `((Bindel (defun foo (x) (+ x x))) (Fateman (defun foo (x) (+ x x))) (Alice (defun foo (x) (* x 2))) (Bob (defun foo (x) (/ x 0.5))) (Carlo (defun foo (y) (/ y 0.5))) (Confused (defun foo (x) (x * 2))) (Dieter (defun foo (x) (* x 2))) (Ed (defun foo (x) (assert (numberp x)) (* x 2))))) (pprint (cluster-programs *codes*))