无涯教程-Clojure - Cond语句函数

18 阅读1分钟

Clojure提供了另一个判断语句,称为" cond" 语句。

Cond - 语法

以下是此声明的一般形式。

cond
(expression evaluation1) statement #1
(expression evaluation2) statement #2
(expression evaluationN) statement #N
:else statement #Default

该语句的一般工作如下-

  • 定义了多个表达式求值,并且每个表达式都有一个要执行的语句。

  • 还有一个默认语句,如果所有先前值都不为true,则执行该默认语句。这是由:else语句定义的。

Cond - 示例

以下是Clojure中" cond"语句的示例。

(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello Learnfk (defn Example [] (def x 5) (cond (= x 5) (println "x is 5") (= x 10)(println "x is 10") :else (println "x is not defined"))) (Example)

在上面的示例中,我们首先将变量x初始化为值5。然后,我们有一个" cond"语句来判断变量" x"的值。基于变量的值,它将执行相关的语句集。

上面的代码产生以下输出。

x is 5

参考链接

www.learnfk.com/clojure/clo…