46 lines
1.6 KiB
Common Lisp
46 lines
1.6 KiB
Common Lisp
;;; LOOPS 6: COUNT, MAXIMIZE, LOOP-FINISH
|
|
;;;
|
|
;;; LOOP accumulates more than lists: COUNT tallies the iterations
|
|
;;; whose test is true, MAXIMIZE tracks the biggest value seen (0
|
|
;;; for an empty run, so WIDEST below answers NIL itself).
|
|
;;;
|
|
;;; LOOP-FINISH leaves the iterations early, gently: the FINALLY
|
|
;;; clause still runs, so (finally (return total)) hands the value
|
|
;;; back either way. NAMED gives a loop a name to leave by:
|
|
;;; (loop named block-name ... (return-from block-name value))
|
|
|
|
;; TODO: How many odd numbers XS holds.
|
|
(defun count-odds (xs)
|
|
(loop for x in xs
|
|
count x))
|
|
|
|
;; TODO: The largest number in XS - NIL when XS is empty.
|
|
(defun widest (xs)
|
|
(loop for x in xs
|
|
sum x))
|
|
|
|
;; TODO: The total you can reach without going over LIMIT: add each
|
|
;; X, but stop the moment the next one would push the total past
|
|
;; LIMIT.
|
|
(defun first-sum-over (xs limit)
|
|
(loop with total = 0
|
|
for x in xs
|
|
do (setf total (+ total x))
|
|
finally (return total)))
|
|
|
|
;;; ------------------------------------------------------------------
|
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
|
;;; them unchanged.
|
|
;;; ------------------------------------------------------------------
|
|
|
|
(check-equal 3 (count-odds '(1 2 3 4 5)))
|
|
(check-equal 0 (count-odds '(2 4)))
|
|
(check-equal 0 (count-odds '()))
|
|
(check-equal 9 (widest '(3 9 2)))
|
|
(check-equal 4 (widest '(4)))
|
|
(check-equal nil (widest '()))
|
|
(check-equal 5 (first-sum-over '(2 3 4) 8))
|
|
(check-equal 9 (first-sum-over '(2 3 4) 100))
|
|
(check-equal 0 (first-sum-over '(9 9) 8))
|
|
(check-equal 0 (first-sum-over '() 5))
|