主要函數(shù)(Bread and butter Functions)
Clojure是函數(shù)式編程的語(yǔ)言(Functional Programming),函數(shù)式的特征:
1.把函數(shù)當(dāng)成一個(gè)普通的值
2.函數(shù)可以作為其他函數(shù)的返回值
3.避免可變狀態(tài),盡量使用Clojure的函數(shù)(Map,filter)替代或者使用遞歸
Map
map函數(shù)會(huì)把函數(shù)的值組合成一個(gè)新的集合缆八,
(map inc [10 20 30]) ; ? (11 21 31)
(map str [10 20 30]) ; ? ("10" "20" "30")
;; You can define the function to be used on-the-fly:
(map (fn [x] (str "=" x "=")) [10 20 30])
;; ? ("=10=" "=20=" "=30=")
;; And `map` knows how to apply the function you give it
;; to mulitple collections in a coordinated way:
(map (fn [x y] (str x y)) [:a :b :c] [1 2 3])
;; ? (":a1" ":b2" ":c3")
map只會(huì)組成一個(gè)最小的集合
(map (fn [x y] (str x y)) [:a :b :c] [1 2 3 4 5 6 7])
;; ? (":a1" ":b2" ":c3")
filter and remove
(filter odd? (range 10))
;; ? (1 3 5 7 9)
(remove odd? (range 10))
;; ? (0 2 4 6 8)
apply
apply功能是分割參數(shù),看例子
(max 1 5 2 8 3)
;; ? 8
(max [1 5 2 8 3]) ;; ERROR
(apply max [1 5 2 8 3])
;; ? 8
也可以這樣疾捍,
(apply max 4 55 [1 5 2 8 3])
;; ? 55
for
這個(gè)不多說(shuō)了耀里,看例子
(for [i (range 10)] i)
;; ? (0 1 2 3 4 5 6 7 8 9)
(for [i (range 10)] (* i i))
;; ? (0 1 4 9 16 25 36 49 64 81)
(for [i (range 10) :when (odd? i)] [i (str "<" i ">")])
;; ? ([1 "<1>"] [3 "<3>"] [5 "<5>"] [7 "<7>"] [9 "<9>"])
reduce
這是一個(gè)相當(dāng)經(jīng)典的函數(shù),會(huì)逐個(gè)進(jìn)行函數(shù)計(jì)算拾氓,舉個(gè)例子
+是reduce第一個(gè)參數(shù)冯挎,第二個(gè)參數(shù)是vector,reduce會(huì)+ 1 2 得到結(jié)果3咙鞍,然后再+ 3 3得到6房官,這樣逐個(gè)的計(jì)算。
(reduce + [1 2 3 4 5])
;; → 1 + 2 [3 4 5]
;; → 3 [3 4 5]
;; → 3 + 3 [4 5]
;; → 6 [4 5]
;; → 6 + 4 [5]
;; → 10 [5]
;; → 10 + 5
;; ? 15
格式是這樣
(reduce (fn [x y] ...) [...])
也可以這樣续滋,多一個(gè)參數(shù)
(reduce + 10 [1 2 3 4 5])
;; ? 25
這是另外一種用法,可以指定一個(gè)初始參數(shù)翰守,并且以這個(gè)初始參數(shù)作為數(shù)據(jù)結(jié)構(gòu),讓函數(shù)去構(gòu)建這個(gè)數(shù)據(jù)結(jié)構(gòu)疲酌。
(reduce (fn [accum x]
(assoc accum
(keyword x)
(str x \- (rand-int 100))))
{}
["hi" "hello" "bye"])
;; → {}
;; → {:hi "hi-29"}
;; → {:hi "hi-29" :hello "hello-42"}
;; ? {:hi "hi-29" :hello "hello-42" :bye "bye-10"}