partial,comp and iterate
partial,創(chuàng)建一個(gè)新的函數(shù),這個(gè)函數(shù)包含一個(gè)已經(jīng)傳遞了參數(shù)的函數(shù),這個(gè)新的函數(shù)只需要補(bǔ)齊參數(shù)就可以了。
(defn lots-of-args [a b c d] (str/join "-" [a b c d]))
;; ? #'user/lots-of-args
(lots-of-args 10 20 30 40)
;; ? "10-20-30-40"
(def fewer-args (partial lots-of-args 10 20 30))
;; ? #'user/fewer-args
(fewer-args 40)
;; ? "10-20-30-40"
(fewer-args 99)
;; ? "10-20-30-99"
(def fewer-args1 (partial lots-of-args 10 20))
(fewer-args1 30 40)
;; ? "10-20-30-40"
comp函數(shù)將多個(gè)函數(shù)組合起來
(defn wrap-in-stars [s] (str "*" s "*"))
(defn wrap-in-equals [s] (str "=" s "="))
(defn wrap-in-ats [s] (str "@" s "@"))
(def wrap-it (comp wrap-in-ats
wrap-in-equals
wrap-in-stars))
(wrap-it "hi")
;; ? "@=*hi*=@"
;; Which is the same as:
(wrap-in-ats (wrap-in-equals (wrap-in-stars "hi")))
;; ? "@=*hi*=@"
(iterate foo x)會(huì)產(chǎn)生一個(gè)無限的懶加載列表,如下:
(x
(foo x)
(foo (foo x))
(foo (foo (foo x)))
...)
獲取5次調(diào)用的方法:
(defn square [x] (* x x))
(take 5 (iterate square 2))
;; ? (2 4 16 256 65536)
循環(huán)和遞歸(Looping and Recursion)
引用類型(Reference Type)
我們一直強(qiáng)調(diào)Clojure是沒有變量的,所有的值都是不可變的,但也不是完全正確,clojure也提供可變的變量,如果需要的話,那就是引用類型。CLojure提供內(nèi)置的支持去做變化。
一共有3種類型的引用:
1.Atoms
2.Refs
3.Agents
創(chuàng)建Atoms的格式如下:
(def my-atom (atom {}))
引用類型是atom,形式是一個(gè)空的hashmap,my-atom指向這個(gè)atom。
看一下例子,如果要修改這個(gè)引用,需要使用@語法,另外swap!是atom專用函數(shù)其他的引用類型會(huì)有其他的函數(shù)。
(def my-atom (atom {:foo 1}))
;; ? #'user/my-atom
@my-atom
;; ? {:foo 1}
(swap! my-atom update-in [:foo] inc)
;; ? {:foo 2}
@my-atom
;; ? {:foo 2}