結(jié)構(gòu)控制
常用的控制判斷,if,and,or,conf
(if motor-turning?
"yes"
"no")
結(jié)構(gòu)是這樣的 (if <test> <then-this> <otherwise-this>)
另外在clojure里面,循環(huán)一般使用map评雌,filter掸读,reduce和for等內(nèi)置函數(shù)委煤,也可以使用loop或者遞歸的方式
這是python的寫法
specific_stuff = []
for i in my_items:
if is_what_i_want(i):
specific_stuff.append(i)
clojure寫法:
(def specific-stuff (filter what-i-want? my-items))
等于,判斷和比較
=或者not=的方式
(if (= tries max-tries)
"you're done"
"keep going")
值的判斷,可以看出來只要內(nèi)容相同都是相等的
(= {:a [1 2 3] :b #{:x :y} :c {:foo 1 :bar 2}}
{:a '(1 2 3) :b #{:y :x} :c {:bar 2 :foo 1}})
;; ? true
數(shù)據(jù)格式不同則不同,但==符號忽略數(shù)據(jù)類型
(= 4 4.0)
;; ? false
(== 4 4.0)
;; ? true
變量(Vars)
賦值
(def the-answer 42)
自定義函數(shù)
使用def+fn
(def my-func
(fn [a b]
(println "adding them!")
(+ a b)))
如何調(diào)用
(my-func 10 20) ; Returns/evaluates-to 30.
也可以使用defn
(defn my-func
"Docstring goes here."
[a b]
(println "adding them!")
(+ a b))
有幾點需要注意:
1.參數(shù)a和b在vector里面刘急,除了沒有賦值
2.你可以在函數(shù)里面做任何操作函荣,但最后一個表達(dá)式是返回值
3.如果用defn显押,函數(shù)名必須在第一行
函數(shù)不一定只返回一個值扳肛,也可以返回一個數(shù)據(jù)結(jié)構(gòu)
(defn foo
[x]
[x (+ x 2) (* x 2)])
也可以傳入數(shù)據(jù)結(jié)構(gòu)
(defn bar
[x]
(println x))
(bar {:a 1 :b 2})
(bar [1 2 3])
可以定義多個參數(shù)
(defn baz
[a b & the-rest]
(println a)
(println b)
(println the-rest))
作者(不是我)喜歡自上而下的寫函數(shù),請看偽代碼:
;; BROKEN pseudocode
(do-it)
(defn do-it
[]
(... (my-func-a ...)))
(defn my-func-a
[...]
(... (my-func-b ...)))
(defn my-func-b ...)
但這樣是不行煮落,clojure在寫一個函數(shù)調(diào)用前需要知道敞峭,例如my-func-a在do-it中被調(diào)用,但是在后面才定義蝉仇,這時我們需要使用declare旋讹,如下:
;; pseudocode
(declare do-it)
(do-it)
(declare my-func-a)
(defn do-it
[]
(... (my-func-a ...)))
(declare my-func-b)
(defn my-func-a
[...]
(... (my-func-b ...)))
(defn my-func-b ...)