1.3.0 permalink Arrow_down_16x16
  • (cond & clauses)
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.

4 Examples top

  • (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"
    
  • user=> (let [grade 85]
             (cond
               (>= grade 90) "A"
               (>= grade 80) "B"
               (>= grade 70) "C"
               (>= grade 60) "D"
               :else "F"))
    "B"
  • ;; See examples for "if" explaining Clojure's idea of logical true
    ;; and logical false.
  • ;; 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!")))
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:534 top

(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))))))
Vars in clojure.core/cond:
Used in 0 other vars

Comments top

No comments for cond. Log in to add a comment.