;;;; exercises-solutions.lisp -- one answer to each of the exercises in ;;;; exercises.lisp. There are many others; yours may well be better. ;;;; ;;;; From the Common Lisp meeting kit of common-lisp.net, under the ;;;; Creative Commons Attribution 4.0 International License. ;;;; ;;;; Load it after exercises.lisp, then (ex:check): ;;;; (load "exercises.lisp") ;;;; (load "exercises-solutions.lisp") ;;;; (ex:check) (in-package :lisp-exercises) ;;; 1 (defun square (x) (* x x)) ;;; 2 (defun greet (name) (format nil "Hello, ~a!" name)) ;;; 3 (defun count-vowels (string) (count-if (lambda (char) (find char "aeiou" :test #'char-equal)) string)) ;;; 4 (defun fizzbuzz (n) (loop for i from 1 to n collect (cond ((zerop (mod i 15)) "FizzBuzz") ((zerop (mod i 3)) "Fizz") ((zerop (mod i 5)) "Buzz") (t (princ-to-string i))))) ;;; 5: the helper carries what has been reversed so far, which makes ;;; the recursion a tail call (defun my-reverse (list) (labels ((rev (rest done) (if (null rest) done (rev (rest rest) (cons (first rest) done))))) (rev list '()))) ;;; 6 (defun word-counts (words) (let ((table (make-hash-table :test #'equal)) (counts '())) (dolist (word words) (incf (gethash word table 0))) (maphash (lambda (word count) (push (cons word count) counts)) table) (sort counts (lambda (a b) (or (> (cdr a) (cdr b)) (and (= (cdr a) (cdr b)) (string< (car a) (car b)))))))) ;;; 7 (defun compose (f g) (lambda (x) (funcall f (funcall g x)))) ;;; 8 (defun caesar (string n) (flet ((shift (char) (if (and (alpha-char-p char) (char<= #\A (char-upcase char) #\Z)) (let ((base (char-code (if (upper-case-p char) #\A #\a)))) (code-char (+ base (mod (+ (- (char-code char) base) n) 26)))) char))) (map 'string #'shift string))) ;;; 9 (defclass point () ((x :initarg :x :reader point-x) (y :initarg :y :reader point-y))) (defmethod distance ((a point) (b point)) (let ((dx (- (point-x a) (point-x b))) (dy (- (point-y a) (point-y b)))) (sqrt (+ (* dx dx) (* dy dy))))) ;;; 10 (defmacro while (test &body body) `(loop (unless ,test (return nil)) ,@body))