Takes a set of test/expr pairs. It evaluates each test one at a
time. If a test returns logical true, cond evaluates and returns
the value of the corresponding expr and doesn't evaluate any of the
other tests or exprs. (cond) returns nil.
(defn pos-neg-or-zero
"Determines whether or not n is positive, negative, or zero"
[n]
(cond
(< n 0) "negative"
(> n 0) "positive"
:else "zero"))
user=> (pos-neg-or-zero 5)
"positive"
user=> (pos-neg-or-zero -1)
"negative"
user=> (pos-neg-or-zero 0)
"zero"
;; Generates a random number compares it to user input
(let [rnd (rand-int 10)
guess (Integer/parseInt (read-line))]
(cond
(= rnd guess) (println "You got my guess right!")
:else (println "Sorry... guess again!")))
Takes a binding-form and a set of test/expr pairs. Evaluates each tes
(defmacro cond
"Takes a set of test/expr pairs. It evaluates each test one at a
time. If a test returns logical true, cond evaluates and returns
the value of the corresponding expr and doesn't evaluate any of the
other tests or exprs. (cond) returns nil."
{:added "1.0"}
[& clauses]
(when clauses
(list 'if (first clauses)
(if (next clauses)
(second clauses)
(throw (IllegalArgumentException.
"cond requires an even number of forms")))
(cons 'clojure.core/cond (next (next clauses))))))
Comments top
1 comment(s) for cond.
We should add a comment in the docstring for the final usage of :else.