cond

added
1.0

ns
clojure.core

type
macro

(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.

                (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!")))
            
                ;; Simple Condition Example 

(defn test-x [x]
\t(cond
\t\t(< x 10) "less than"
\t\t(> x 20) "greater than"
\t)
)

============test============
(test-x 9)

=> "less than"
            
                (defn print-cond [xx] 
  (cond 
    (< xx 6) "less than 6"
    (< xx 8) "less than 8"
    :else "Greater than 8"))
=> #'aurora.system/print-cond
(print-cond 5)
=> "less than 6"
(print-cond 7)
=> "less than 8"
(print-cond 8)
=> "Greater than 8"
(print-cond 10)
=> "Greater than 8"

            
                ;; If a condition is not matched `nil` will be returned
(cond
  false "sumfin")
;;=> nil