typestar

cond, when & unless in Lisp

cond is the multi-branch conditional; when and unless cover the one-sided cases.

;; cond walks its clauses in order and takes the first test that holds
(defun grade (score)
  (cond ((>= score 90) "A")
        ((>= score 80) "B")
        ((>= score 70) "C")
        ((>= score 60) "D")
        (t "F")))

(defparameter *scores* '(96 84 71 58))

;; when and unless are one-armed ifs, each with an implicit progn body
(dolist (score *scores*)
  (format t "~a maps to ~a~%" score (grade score))
  (when (>= score 90) (format t "  honor roll~%"))
  (unless (>= score 60) (format t "  retake scheduled~%")))

How it works

  1. grade tests four ranges in order and lands on the (t "F") clause when none match.
  2. A dolist runs every score in *scores* through it.
  3. when adds an honor-roll line above 90 and unless flags a retake below 60.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
480
Tokens
102
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 1 of 3 in Control flow, step 7 of 27 in Language basics.

← Previous Next →