學(xué)習(xí)Clojure第十一、第十二天

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}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容