The following section of functions gives examples of simple control flow. As you gain more experience with Clojure, you will discover more functional ways to achieve the same (or better) results.
Hint Although these functions may seem similar to other non-functional languages, there are subtle differences
if function you can test if an expression evaluates to true. If it is true, the first value is returned, if its false the second value is returned.
Here is a simple example to see if one number is bigger that another
Here is an example of an condition inside an anonymous function.
When a condition is true, then return the value of evaluating the next expression. If the condition is false, then return
When one of these things is true, do this, else default
Return the associated value of the first condition that is true, or return the default value specified by
(cond (= 7 (inc 2)) "(inc 2) is not 7, so this condition is false" (= 16 (* 8 2)) "This is the first correct condition so its associated expression is returned" (zero? (- (* 8 8) 64)) "This is true but not returned as a previous condition is true" :otherwise "None of the above are true") ;; => "This is the first correct condition so its associated expression is returned"
for function you can Iterate through the values in a collection and evaluate each value in tern with with a condition, using either
Do something while the condition is true
Here is a simple while example that uses a (mutable) counter and prints out the results to the repl window.
This example uses mutable state and causes a side effect by printing to the repl. Both these kinds of things are typically kept to a minimum in Clojure.
TODO An alternative would be to use use the iteration over a collection to control the while condition