41 lines
1.3 KiB
Common Lisp
41 lines
1.3 KiB
Common Lisp
;;; CONDITIONS 5: REPORTS, WARN, SIGNAL (solution)
|
|
|
|
(define-condition low-battery (condition) ())
|
|
|
|
(define-condition empty-cart (error)
|
|
()
|
|
(:report "The cart is empty - nothing to check out."))
|
|
|
|
(defun checkout (items)
|
|
(when (null items)
|
|
(error 'empty-cart))
|
|
(list 'order items))
|
|
|
|
(defun battery-check (percent)
|
|
(when (< percent 20)
|
|
(warn "battery ~a%!" percent))
|
|
(list 'battery percent))
|
|
|
|
(defun check-battery (percent)
|
|
(when (<= percent 10)
|
|
(signal 'low-battery))
|
|
(list 'battery percent))
|
|
|
|
;;; ------------------------------------------------------------------
|
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
|
;;; them unchanged.
|
|
;;; ------------------------------------------------------------------
|
|
|
|
(check-equal '(order (milk)) (checkout '(milk)))
|
|
(check-error (checkout '()) 'empty-cart)
|
|
(check-equal "The cart is empty - nothing to check out."
|
|
(handler-case (checkout '())
|
|
(empty-cart (c) (format nil "~a" c))))
|
|
(check-equal '(battery 15) (battery-check 15))
|
|
(check-equal '(battery 90) (battery-check 90))
|
|
(check-equal :noticed (handler-case (warn "battery low")
|
|
(warning () :noticed)))
|
|
(check-equal :swapped (handler-case (check-battery 5)
|
|
(low-battery () :swapped)))
|
|
(check-equal '(battery 20) (check-battery 20))
|