;;; CONDITIONALS 5: CASE AND ECASE ;;; ;;; COND's tidy cousin for dispatching on one value: ;;; ;;; (case fruit ;;; ((apple banana) "cheap") ;;; ((mango) "pricey") ;;; (t "unknown")) ;;; ;;; The keys are compared with EQL, and a (t ...) clause catches ;;; everything else. Leave the fallback out and CASE quietly answers ;;; NIL. ECASE is CASE without the safety net: no matching key, and ;;; it signals a TYPE-ERROR instead. ;; TODO: Fruits are priced: apples and bananas "cheap", mangoes and ;; durians "pricey", anything else "unknown". (defun rate-fruit (fruit) (case fruit ((apple banana) "cheap") ((mango) "pricey"))) ;; TODO: :open means "come in", :closed means "knock first" - and ;; any other state is not a state at all: let ECASE complain. (defun door-state (state) (case state (:open "come in") (:closed "knock first"))) ;;; ------------------------------------------------------------------ ;;; Checks. Read them - they tell you what to aim for - but leave ;;; them unchanged. ;;; ------------------------------------------------------------------ (check-equal "cheap" (rate-fruit 'apple)) (check-equal "cheap" (rate-fruit 'banana)) (check-equal "pricey" (rate-fruit 'mango)) (check-equal "pricey" (rate-fruit 'durian)) (check-equal "unknown" (rate-fruit 'kiwi)) (check-equal "come in" (door-state :open)) (check-equal "knock first" (door-state :closed)) (check-error (door-state :ajar) 'type-error)