Flow Control

if

cond

Boolean logic

What is flow control?

Decisions how to react

“Flow control” is the programming term for deciding how to react to
a given circumstance. We make decisions like this all the time. If
it’s a nice day out, then we should visit the park; otherwise we
should stay inside and play board games. If your car’s tank is
empty, then you should visit a gas station; otherwise you should
continue to your destination.

Testing conditions to react

Software is also full of these decisions. If the user’s input is
valid, then we should save their data; otherwise we show an error
message. The common pattern here is that you test some condition and
react differently based on whether the condition is true or false.

if

In Clojure, the most basic tool we have for the flow control is the if
operator. It allows you to choose between two options depending upon a condition.

cond

The if operator takes only one predicate.
When we want to use multiple predicates, if is not a good option.
We have to write nested, nested, … and nested if conditions.
To branch to multiple situations, cond operator works well.

Boolean logic with and, or, and not

if statements are not limited to testing only one thing. You can
test multiple conditions using boolean logic. Boolean logic refers
to combining and changing the results of predicates using and,
or, and not.

If you’ve never seen this concept in programming before, remember
that it follows the common sense way you look at things normally. Is
this and that true? Only if both are true. Is this or that true?
Yes, if either – or both! – are. Is this not true? Yes, if it’s
false.

Truthy and falsey table

and, or, and not work like other functions (they aren’t
exactly functions, but work like them), so they are in prefix
notation, like we’ve seen with arithmetic.

x

y

(and x y)

(or x y)

(not x)

(not y)

false

false

false

false

true

true

true

false

false

true

false

true

true

true

true

true

false

false

false

true

false

true

true

false

and, or, and not combination

and, or, and not can be combined. This can be hard to read.
Here’s an example:

(defn leap-year?
"Every four years, except years divisible by 100, but yes for years divisible by 400."
[year]
(and (zero? (mod year 4))
(or (zero? (mod year 400))
(not (zero? (mod year 100))))))