clojure学习(1)——判断语句

clojure是操作符前缀的语言。

;为单行注释

nil相当于Java里面的null,if判断里面的false

if语句除了false和nil,其他都为true,如果else后面没内容,为false时就返回nil。

user=> (defn is-small [number] (if (< number 100) "yes" "no"))
#'user/is-small
user=> (is-small 20)
"yes"
user=> (is-small 150)
"no"

user=> (defn is-small [number] (if (< number 100) "yes" ))
#'user/is-small
user=> (is-small 110)
nil

 

if-not:和if相反的判断

user=> (if-not (zero? 0) "no" "yes")
"yes"
user=> (if-not (zero? 123) "no" "yes")
"no"

 

if-let 用法:第一个参数为绑定变量,第二个参数为表达式。并根据第二个表达式参数返回的值确定执行then、else语句。

user=> (defn if-let-test [arg] (if-let [x arg] "true" "false"))
#'user/if-let-test
user=> (if-let-test 1)
"true"
user=> (if-let-test nil)
"false"
user=> (if-let-test false)
"false"

 

when

当不为false或nil时才执行后面的语句,否则返回nil

user=> (when false (println "is true") "return true")
nil
user=> (when false (println "is true") "return true" "return false")
nil
user=> (when true (println "is true") "return true" "return false")
is true
"return false"
user=> (def has-value (when true (println "ni hao") "returned value"))
ni hao
#'user/has-value
user=> has-value
"returned value"

 

when-not

为false或nil时候才执行后面语句,否则返回nil

user=> (when-not false (println "is false") "return true" "return false")
is false
"return false"
user=> (when-not false (println "is false") (println "return true") "return false")
is false
return true
"return false"

 

when-let

类似if-let,当绑定变量部位false或nil才执行后面语句,否则返回nil

user=> (when-let [a true] (println "true") "return true")
true
"return true"
user=> (when-let [a false] (println "true"))
nil
user=> (when-let [a nil] (println "true"))

 

cond

类似Java里面的switch-case-default语句

user=> (defn f [n] (cond (< n 0) "<0" (< n 10) "<10" :else ">=10"))
#'user/f
user=> (f -56)
"<0"
user=> (f 56)
">=10"
user=> (f 156)
">=10"
user=> (f 6)
"<10"

 

case

类似switch里的case

user=> (let [mystr "ni hao"]
(case mystr
"" 0
"ni hao" (count mystr)))
6

user=> (let [mystr "no one"]
(case mystr
"" 0
"ni hao" (count mystr)
"default"))
"default"

 

多值匹配

user=> (defn f [x] (case x
(5 10) "*5"
(3 6 9) "*3"
"others"))
#'user/f
user=> (f 5)
"*5"
user=> (f 10)
"*5"
user=> (f 3)
"*3"
user=> (f 11)
"others"

 

do

执行多条语句,返回最后一条语句值

user=> (def v (do (println 123) (println 321) (println 543) 23 0))
123
321
543
#'user/v
user=> v
0

 

 

发表回复

您的电子邮箱地址不会被公开。

粤ICP备17041560号-2