how to use clojure cond

Using cond in Clojure

The cond function in Clojure is used for conditional branching. It allows you to evaluate multiple conditions and execute different expressions based on the result of each condition. Here's the syntax for using cond:

(cond
  condition1 expression1
  condition2 expression2
  ...
  conditionN expressionN
  :else default-expression)
  • condition1, condition2, ..., conditionN are the conditions to be evaluated.
  • expression1, expression2, ..., expressionN are the expressions to be executed if the corresponding condition is true.
  • :else is an optional keyword that represents the default condition if none of the previous conditions are true.
  • default-expression is the expression to be executed if none of the conditions are true.

Example:

(defn get-grade [score]
  (cond
    (< score 60) "F"
    (< score 70) "D"
    (< score 80) "C"
    (< score 90) "B"
    :else "A"))

In this example, the get-grade function takes a score as input and returns the corresponding grade based on the score. The cond expression evaluates the score against multiple conditions and returns the appropriate grade.

Please note that the conditions are evaluated in order, and the first condition that evaluates to true will execute its corresponding expression. If none of the conditions are true, the :else expression (if provided) will be executed.

I hope this helps! Let me know if you have any further questions.