Learn/Clojure/4. Making decisions
Lesson 4 of 8
Sign in

Clojure, lesson 4

Making decisions

Programs often need to choose: charge children less, warn when it's too hot. In Clojure, every decision is an expression that returns a value, so you can use a decision anywhere a value is expected.

if

if takes a test, a "then" form and an "else" form:

Only the chosen branch is evaluated. If you leave out the else form and the test fails, if returns nil. Each branch is a single form; to do several things in one branch, wrap them in (do ...), which runs its forms in order and returns the last one.

Truthiness

Clojure's tests are simple: only false and nil count as false. Everything else, including , and empty collections, counts as true. This is why functions like return on bad input: you can test the result directly.

2 exercises to try what you just read.

Exercise 1

Ticket price

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year

Press Ctrl Enter or Check to test your code.

0
""
parse-long
nil

Comparisons and logic

Comparisons are functions too, and many accept more than two arguments:

Combine tests with and, or and not:

and and or stop as soon as the answer is known. Functions ending in ? are predicates that return true or false: zero?, pos?, neg?, even?, odd?, nil?.

when: one branch, several steps

When there is no else branch, use when. It takes a test and any number of body forms, and returns nil if the test is false. Seeing when tells the reader "there is nothing to do otherwise":

cond: many branches

For more than two outcomes, cond takes pairs of test and result. The first test that is truthy wins. :else is a keyword, which is always truthy, so it works as the "otherwise" case:

(defn defines a function; the next lessons cover it properly.)

case: matching exact values

When you compare one value against fixed constants, case is fast and tidy. The final unpaired form is the default:

Without a default, an unmatched value throws an error, so always include one.

Further reading

  • Learn Clojure: Flow Control
  • Special Forms: if and do

A cinema charges by age: children under 13 pay 5, people aged 65 or older pay 7, and everyone else pays 12. Read an age (a whole number, 0 or more) and print the price.

Sample input:

Sample output:

A year is a leap year if it is divisible by 4, except years divisible by 100, which are leap years only if they are also divisible by 400. Read a year and print leap or common.

Sample input:

Sample output:

(let [temp (parse-long (read-line))
      advice (if (> temp 25) "Wear a hat" "Bring a jacket")]
  (println advice))
(= 3 3)            ; true   (works on numbers, strings, collections...)
(not= "a" "b")     ; true
(< 1 2 3)          ; true   (1 < 2 < 3: checks the whole chain)
(<= 18 age 65)     ; is age between 18 and 65, inclusive?
(and (>= age 8) (>= height 120))
(or (= day "Sat") (= day "Sun"))
(not (zero? n))
(when (> score best)
  (println "New record!")
  (println "Well done."))
(defn describe [temp]
  (cond
    (< temp 0) "freezing"
    (< temp 20) "mild"
    :else "warm"))
(case day
  "Sat" "weekend"
  "Sun" "weekend"
  "weekday")
70
Price: 7
2024
leap