Skip to content
Lesson 6 of 10

Step 1 of 5 · Reading · ~1 min

Learn

Flow and Recursion

Conditionals are expressions — they return values.

if takes a test, then-branch, optional else-branch:

(if (> x 0)
  "positive"
  "non-positive")

cond for multiple branches:

(cond
  (>= score 90) "A"
  (>= score 80) "B"
  (>= score 70) "C"
  :else "F")

:else is just the keyword :else — it's truthy and serves as the default. You could use true or :default instead; :else is convention.

when is if with no else and an implicit do for multiple statements:

(when (= status "ready")
  (log-it "starting")
  (start-process))

Falsy values: only false and nil. Empty collections, 0, "" are all truthy.

Testing a value

= compares values structurally, and it wants at least two of them:

(= 3 3)              ; true
(= [1 2] '(1 2))     ; true  -- same elements, same order
(= 3)                ; true  -- ALWAYS true; one argument is nothing to compare

That last line is the trap. (= (mod n 15)) looks like a divisibility test and is in fact a constant true, so the first branch of your cond wins for every input.

mod gives the remainder, and zero? asks the question you actually mean:

(mod 9 3)            ; 0
(mod 10 3)           ; 1
(zero? (mod 9 3))    ; true
(= 0 (mod 9 3))      ; true  -- same thing, spelled out
Up nextRecursion and recurFlow and Recursion

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…