A Look at cond Function

Here is a look at the “cond” function in Clojure. It’s like “if”, but with more conditions.

 

user> (defn test-num-same-line [x]
  (cond
    (< x 10) "less than"
    (> x 20) "greater than"))
#'user/test-num-same-line
user> (test-num-same-line 9)
"less than"
user> (test-num-same-line 29)
"greater than"
user> (test-num-same-line 19)
nil
;; the conditions and expressions can also be on different lines
user> (defn test-num-diff-line [x]
  (cond
    (< x 10)
    "less than"
    (> x 20)
    "greater than"))
#'user/test-num-diff-line
user> (test-num-diff-line 9)
"less than"
user> (test-num-diff-line 29)
"greater than"
user> (test-num-diff-line 19)
nil
;; let us come up with an else or "catch-all" condition
user> (defn test-num-with-else [x]
  (cond
    (< x 10) "less than"
    (> x 20) "greater than"
    :else "Between 10 and 20"))
#'user/test-num-with-else
user> (test-num-with-else 9)
"less than"
user> (test-num-with-else 29)
"greater than"
user> (test-num-with-else 19)
"Between 10 and 20"
;; you can use any keyword for the last condition; it does not have to be "else"
user> (defn test-num-with-other-keyword [x]
  (cond
    (< x 10) "less than"
    (> x 20) "greater than"
    :north "Between 10 and 20"))
#'user/test-num-with-other-keyword
#'user/test-num-with-other-keyword
user> (test-num-with-other-keyword 9)
"less than"
user> (test-num-with-other-keyword 29)
"greater than"
user> (test-num-with-other-keyword 19)
"Between 10 and 20"

You’re welcome.

There are 161 words in this article.