Files
lisplings/exercises/15_clos/clos6.lisp
T

50 lines
1.5 KiB
Common Lisp

;;; CLOS 6: CALL-NEXT-METHOD AND NEXT-METHOD-P
;;;
;;; A method can stand on the one above it: CALL-NEXT-METHOD runs
;;; the next most specific method and hands its answer back, so you
;;; can build on it. When there is no next method, CALL-NEXT-METHOD
;;; itself errors - NEXT-METHOD-P asks first.
;;;
;;; (defmethod speak ((d dog))
;;; (concatenate 'string (call-next-method) " Woof!"))
(defclass animal () ())
(defclass dog (animal) ())
(defclass cat (animal) ())
(defgeneric announce (a))
(defmethod announce ((a animal))
"I am an animal.")
(defgeneric purr (a))
(defmethod purr ((a animal))
"prrr-from-animal")
(defgeneric hiss (a))
;; TODO: A DOG announces what an animal announces, then adds
;; " Woof!".
(defmethod announce ((d dog))
"Woof!")
;; TODO: CAT purrs: if a method above you exists, use its answer;
;; otherwise say "Prrr" - and CAT hisses the same way, though HISS
;; has no method above CAT at all.
(defmethod purr ((c cat))
"Prrr")
(defmethod hiss ((c cat))
(call-next-method))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal "I am an animal. Woof!" (announce (make-instance 'dog)))
(check-equal "I am an animal." (announce (make-instance 'animal)))
(check-equal "prrr-from-animal" (purr (make-instance 'cat)))
(check-equal "Prrr" (hiss (make-instance 'cat)))