Recursion basics in Lisp
Two recursions over the same list of rainfall readings, differing in where the answer accumulates.
;; the base case stops the descent; each call peels off one reading
(defun total-rainfall (readings)
(if (null readings)
0
(+ (first readings) (total-rainfall (rest readings)))))
;; carrying an accumulator turns the same walk into a tail call
(defun count-dry-days (readings &optional (tally 0))
(cond ((null readings) tally)
((zerop (first readings))
(count-dry-days (rest readings) (1+ tally)))
(t (count-dry-days (rest readings) tally))))
(defparameter *week* '(0 12 0 3 0 0 8))
(format t "~a mm fell this week~%" (total-rainfall *week*))
(format t "~a of the days were dry~%" (count-dry-days *week*))
How it works
total-rainfallreturns 0 on(null readings)and otherwise adds(first readings)to the sum of therest.count-dry-dayscarries the running total in an&optionaltallyargument instead.- Its
condbumps the tally with(1+ tally)whenzeropholds and passes it through unchanged otherwise.
Keywords and builtins used here
conddefparameterdefunfirstformatifnullrestzerop
The run, in numbers
- Lines
- 16
- Characters to type
- 606
- Tokens
- 116
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 93 seconds.
Step 3 of 3 in Control flow, step 9 of 27 in Language basics.