Let’s take a look at some entry level conditional flow control techniques in clojure.
The form for if then is pretty simple– (if [true/false expression] [expression to call if truthy] [expression to call if falsey])
. The final else (fn to call if falsey) is optional.
In clojure, both false
and nil
evaluate to logical false. Its kinda like JS in that regard.
Be careful with the placement of your if statement. Coming from JS/.NET i would’ve expected the result from the if
to be returned as the final return, but nope– the rule is still that the last expression/value is what is returned:
Good to watch for!
I’m kinda surprised that a language would have an if-not. But then again F#’s not
operator was a bit strange at first as well. I guess its nice to not have to negate the test.
when
and when-not
are effectively else
-less if
statements. Example:
If you’re looking for else if
style flow, look no farther than cond
. Notice how you end a cond
statement via the :else
keyword.
condp
is awesome. This is the first time I’ve seen a language that has something similar to a case/switch statement that isn’t horrendously ugly. What’s more, it seems like there are some ways to get condp
close to pattern matching– though I won’t cover it here (because it’s still above my level).
Notice how with condp instead of starting the “test expressions” with real functions, you can start them with real values for if you’re looking to match exactly to what you’re looking for.
Alternatively, you can use an expression and then the ::>
keyword. With this form, (from what I can tell) any expression that evaluates to true will work. Notice how in the following example we used true ::>
as a “catch-all.”
If you don’t have a matching expression/clause expect an exception to be thrown.