2.5 流控制
if
Clojure的if计算第一个参数值,如果第一个参数值为true,则返回第二个参数值;如果为false,则返回nil或第三个参数值(如果有第三个参数)
user=> (defn is-small? [number]
(if (< number 100) "yes"))
#'user/is-small?
user=> (is-small? 50)
"yes"
user=> (is-small? 500)
nil
user=> (defn is-small? [number]
(if (< number 100) "yes" "no"))
#'user/is-small?
user=> (is-small? 500)
"no"
说明:if每个分支只能有一个form
do
do后面能跟多个form,返回最后一个。如:
user=> (defn is-small? [number]
(if (< number 100)
"yes"
(do
(println "Saw a big number" number)
"no")))
#'user/is-small?
user=> (is-small? 200)
Saw a big number 200
"no"
loop/recur
loop语法:
(loop [bindings *] exprs*)
loop形式像let一样,建立绑定(bindings),然后计算表达式(exprs)值,但是它可以使用recur形式设置循环点:
(recur exprs*)
recur给loop的绑定赋予新值,然后返回loop开头。如:
user=> (loop [result [] x 5]
(if (zero? x)
result
(recur (conj result x) (dec x))))
[5 4 3 2 1]
recur也可以返回到函数开头,实现函数体循环:
user=> (defn countdown [result x]
(if (zero? x)
result
(recur (conj result x) (dec x))))
#'user/countdown
user=> (countdown [] 5)
[5 4 3 2 1]
for循环在哪里?
Clojure没有for循环和直接的可变变量。Clojure的for不是循环而是序列映射。
user=> (defn indexed [coll] (map vector (iterate inc 0) coll))
#'user/indexed
user=> (defn index-filter [pred coll]
(when pred
(for [[idx elt] (indexed coll) :when (pred elt)] idx)))
#'user/index-filter
user=> (index-filter #{\a \b} "abcdbbb")
(0 1 4 5 6)
if
Clojure的if计算第一个参数值,如果第一个参数值为true,则返回第二个参数值;如果为false,则返回nil或第三个参数值(如果有第三个参数)
user=> (defn is-small? [number]
(if (< number 100) "yes"))
#'user/is-small?
user=> (is-small? 50)
"yes"
user=> (is-small? 500)
nil
user=> (defn is-small? [number]
(if (< number 100) "yes" "no"))
#'user/is-small?
user=> (is-small? 500)
"no"
说明:if每个分支只能有一个form
do
do后面能跟多个form,返回最后一个。如:
user=> (defn is-small? [number]
(if (< number 100)
"yes"
(do
(println "Saw a big number" number)
"no")))
#'user/is-small?
user=> (is-small? 200)
Saw a big number 200
"no"
loop/recur
loop语法:
(loop [bindings *] exprs*)
loop形式像let一样,建立绑定(bindings),然后计算表达式(exprs)值,但是它可以使用recur形式设置循环点:
(recur exprs*)
recur给loop的绑定赋予新值,然后返回loop开头。如:
user=> (loop [result [] x 5]
(if (zero? x)
result
(recur (conj result x) (dec x))))
[5 4 3 2 1]
recur也可以返回到函数开头,实现函数体循环:
user=> (defn countdown [result x]
(if (zero? x)
result
(recur (conj result x) (dec x))))
#'user/countdown
user=> (countdown [] 5)
[5 4 3 2 1]
for循环在哪里?
Clojure没有for循环和直接的可变变量。Clojure的for不是循环而是序列映射。
user=> (defn indexed [coll] (map vector (iterate inc 0) coll))
#'user/indexed
user=> (defn index-filter [pred coll]
(when pred
(for [[idx elt] (indexed coll) :when (pred elt)] idx)))
#'user/index-filter
user=> (index-filter #{\a \b} "abcdbbb")
(0 1 4 5 6)