Fundamentos de recursión en Lisp
Dos recursiones sobre la misma lista de lluvias, distintas en dónde se acumula la respuesta.
;; 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*))
Cómo funciona
total-rainfalldevuelve 0 con(null readings)y si no suma(first readings)al total delrest.count-dry-daysen cambio lleva el total corriente en un argumento&optionaltally.- Su
condsube el conteo con(1+ tally)cuandozeropse cumple y lo pasa sin cambios si no.
Palabras clave y builtins usados aquí
conddefparameterdefunfirstformatifnullrestzerop
El intento, en números
- Líneas
- 16
- Caracteres a escribir
- 606
- Tokens
- 116
- Ritmo de tres estrellas
- 75 tpm
Al ritmo de tres estrellas de 75 tokens por minuto, este intento toma unos 93 segundos.
Paso 3 de 3 en Control de flujo; paso 9 de 27 en Fundamentos del lenguaje.