Files
lisplings/exercises/10_loops/loops4.lisp
T

33 lines
1.2 KiB
Common Lisp

;;; LOOPS 4: LOOP'S OTHER CLAUSES
;;;
;;; FOR X = 1 THEN (* X 2) keeps a running value: 1 the first time
;;; round, the THEN expression on every step after. WITH binds a
;;; variable once, for the whole loop. UNTIL stops the loop when its
;;; test turns true; WHILE is the same test upside down.
;;;
;;; (loop repeat 4 for x = 1 then (* x 2) collect x) => (1 2 4 8)
;; TODO: The first N doublings of 1: (1 2 4 8) for N = 4.
(defun doublings (n)
(loop for i from 1 to n
collect i))
;; TODO: The prices in XS, until adding the next one would push the
;; running total to CAP or past it.
(defun cart-until-cap (xs cap)
(loop for p in xs
until (>= p cap)
collect p))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check-equal '(1 2 4 8) (doublings 4))
(check-equal '(1) (doublings 1))
(check-equal '() (doublings 0))
(check-equal '(3 5) (cart-until-cap '(3 5 2 8) 10))
(check-equal '() (cart-until-cap '(20 1) 10))
(check-equal '(1 2) (cart-until-cap '(1 2 3 4) 6))