let & let* in Lisp
let binds all its names at once; let* builds each one on the last.
;; let binds in parallel; let* lets each binding see the ones above it
(defun cart-total (subtotal)
(let* ((tax-rate 0.08)
(tax (* subtotal tax-rate))
(shipping (if (> subtotal 50) 0 5.95)))
(+ subtotal tax shipping)))
(defparameter *basket* 40)
;; the inner binding shadows the outer one for the length of its body
(let ((discount 0.10))
(format t "everyone gets ~a~%" discount)
(let ((discount 0.25))
(format t "members get ~a~%" discount))
(format t "and back to ~a~%" discount))
(format t "cart comes to ~$~%" (cart-total *basket*))
How it works
- Inside
cart-total,let*letstaxuse thetax-ratebound just above it. - The
shippingbinding waives the 5.95 charge oncesubtotalclears 50. - A nested
letrebindsdiscountto 0.25, and the outer 0.10 returns as soon as that body ends.
Keywords and builtins used here
defparameterdefunformatiflet
The run, in numbers
- Lines
- 17
- Characters to type
- 539
- Tokens
- 95
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 76 seconds.
Step 2 of 3 in Values & bindings, step 2 of 27 in Language basics.