typestar

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

  1. Inside cart-total, let* lets tax use the tax-rate bound just above it.
  2. The shipping binding waives the 5.95 charge once subtotal clears 50.
  3. A nested let rebinds discount to 0.25, and the outer 0.10 returns as soon as that body ends.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Values & bindings, step 2 of 27 in Language basics.

← Previous Next →