Multiple values in Lisp
Splits a lap time into minutes and seconds, then contrasts floor with truncate.
;; A form can return several values: VALUES packages them up and
;; MULTIPLE-VALUE-BIND takes them apart again.
(defun split-seconds (total)
"Return TOTAL seconds as whole minutes and leftover seconds."
(multiple-value-bind (minutes rest) (floor total 60)
(values minutes rest)))
(multiple-value-bind (minutes seconds) (split-seconds 227)
(format t "lap time ~d:~2,'0d~%" minutes seconds))
;; FLOOR rounds down and TRUNCATE rounds toward zero, so the two
;; disagree on negative numbers. NTH-VALUE picks out the remainder.
(format t "floor ~a ~a~%" (floor -7 2) (nth-value 1 (floor -7 2)))
(format t "truncate ~a ~a~%" (truncate -7 2) (nth-value 1 (truncate -7 2)))
How it works
split-secondscalls(floor total 60)insidemultiple-value-bindand returns both parts withvalues.- The caller unpacks them with another
multiple-value-bindand prints~d:~2,'0d. (floor -7 2)and(truncate -7 2)differ on negatives;(nth-value 1 (floor -7 2))pulls out the remainder.
Keywords and builtins used here
defunfloorformatresttruncatevalues
The run, in numbers
- Lines
- 14
- Characters to type
- 670
- Tokens
- 85
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 73 seconds.
Step 3 of 3 in Functions, step 12 of 27 in Language basics.