cond
The cond
macro works like the way the if
conditional
does branching. Unlike if
, cond
can take multiple tests and corresponding clauses.
Since Clojure doesn’t have else if, cond is used for that purpose.
The example below needs three tests.
In this case, we can’t use if
, but we can do this with cond
.
The syntax is: (cond & clauses)
user> (defn what-to-do
[temp]
(cond
(> temp 65) "I'll enjoy walking at a park."
(> temp 45) "I'll spend time at a cafe."
:else "I'll curl up in my bed."))
#'user/what-to-do
user> (what-to-do 70)
"I'll enjoy walking at a park."
user> (what-to-do 50)
"I'll spend time at a cafe."
user> (what-to-do 30)
"I'll curl up in my bed."
Clojure has condp
macro also.
The usage is similar to cond
, but it takes a part of test right after the condp.
The syntax is: (condp pred expr & clauses)
user> (defn what-to-do-p
[temp]
(condp < temp
65 "I'll enjoy walking at a park."
45 "I'll spend time at a cafe."
"I'll curl up in my bed"))
#'user/what-to-do-p
user> (what-to-do-p 70)
"I'll enjoy walking at a park."
user> (what-to-do-p 50)
"I'll spend time at a cafe."
user> (what-to-do-p 30)
"I'll curl up in my bed"
ClojureDocs
Introduction to Clojure, Control Structures
http://clojure-doc.org/articles/tutorials/introduction.html#control-structures
Clojure from the ground up: macros, Control flow
http://aphyr.com/posts/305-clojure-from-the-ground-up-macros
GetClojure