条件语句

if

if 语句是常用的条件语句,语法为

(if 条件 true返回 false返回)
user=> (if true "I'm true" "I'm false")
"I'm true"
user=> (if false "I'm true" "I'm false")
"I'm false"

条件值

在clojure中,当作为条件值时所有的值都代表true或者false,其中只有只有false本身和 nil代表false,其他的所有值都代表true

user=> (if (Object.) :truthy :falsey) ; objects are true
:truthy
user=> (if [] :truthy :falsey) ; empty collections are true
:truthy
user=> (if 0 :truthy :falsey) ; zero is true
:truthy

do

可以用do语句替换返回值来写更复杂的语句

user=> (if false
  (do (println "I'm true") true)
  (do (println "I'm false") false))
I'm false
false

when

when语句可以理解为只有条件为true的时候才会执行的if语句,它没有false分支

user=> (when 1 (print "Hello ") (println "World !") 2) ;;不需要do语句因为只有true分支 所以可以写多个表达式
Hello World !
2

cond

cond是多个验证语句的集合,返回第一个条件为true的表达式

user=> (let [x 4]
  #=>   (cond
  #=>     (> x 2) "first"
  #_=>     (< x 10) "second"))

cond 和 else

习惯性的可以用:else作为cond语句的缺省条件

user=> (let [x 4]
  #=>   (cond
  #=>     (< x 2) "first"
  #=>     (> x 10) "second"
  #=>     :else  "third"))
"third"
user=> (let [x 4]
  #=>   (cond
  #=>     (< x 2) "first"
  #=>     (> x 10) "second"
  #=>     1  "third"))   ;;其实用其他条件也可以
"third"

case

case语句是匹配条件语句

user=> (let [name "Tom"]
  #=>      (case name
  #=>        "Jack"  "first"
  #=>        "Tom"   "second"))
"second"

如果没有匹配项,会抛出异常

user=> (let [name "Ken"]
  #=>      (case name
  #=>        "Jack"  "first"
  #=>        "Tom"   "second"))
Execution error (IllegalArgumentException) at user/eval2061 (REPL:2).
No matching clause: Ken

如果在在语句最后加一个表达式可以当做缺省项

user=> (let [name "Ken"]
  #=>      (case name
  #=>        "Jack"  "first"
  #=>        "Tom"   "second"
  #=>        "third"))
"third"