36 lines
1.0 KiB
Common Lisp
36 lines
1.0 KiB
Common Lisp
;;; LOOPS 6: COUNT, MAXIMIZE, LOOP-FINISH (solution)
|
|
|
|
(defun count-odds (xs)
|
|
(loop for x in xs
|
|
count (oddp x)))
|
|
|
|
(defun widest (xs)
|
|
(if (null xs)
|
|
nil
|
|
(loop for x in xs
|
|
maximize x)))
|
|
|
|
(defun first-sum-over (xs limit)
|
|
(loop with total = 0
|
|
for x in xs
|
|
do (if (> (+ total x) limit)
|
|
(loop-finish)
|
|
(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))
|