2017-07-08 65 views
2

的使用,我知道到目前爲止都在向量:除了地圖和向量,Clojure還有其他用途嗎?

(get [1 2 3 4] 2) ; => 3 

,並在地圖上:

(get {:a "a" :b "B" :c "c"} :c) ; => "c" 

從技術文檔,它說:

clojure.core /獲取([圖鍵] [地圖鍵未找到])

如果鍵不存在,則返回映射到鍵的值,未找到或無。

回答

9

除了地圖和載體,共同使用了得到是字符串:

(get "Cthulhu" 2) ;; => \h 

得到也適用於集和本地Java(腳本)陣列。在ClojureScript和JavaScript間-OP一個可能的用途:

(def js-array (-> (js/Array 10) ;Create and fill native JS array 
        (.fill "a") 
        (.map (fn [_ i] i)))) 
(get js-array 3) ; => 3 

再舉一個例子,讓作品在一組查找的資料:

(get #{:b :c :a} :c) ;;=> :c 

注意,它不以工作(整理)設置和索引,例如:

(get (sorted-set :b :a :c) 1) ;; throws exception 

此外,地圖,矢量和集作爲其成員的功能,讓你可以經常避免使用得到乾脆:

(#{:a :b :c} :b) ; => :b 
({:a 1 :b 2 :c 3} :b) ; => 2 
([:a :b :c] 1) ; => :b 

使用的優勢得到他們是可以提供一個默認值:

(get {:a :b :c} :d) ; => nil 
(get {:a :b :c} :d :not-found) ; => :not-found 

又見@Thumbnail's answer瞭解如何讓引擎蓋下作品。

+0

注意,對於地圖,你可以使用'(({:a 1:b 2}:c 10)'指定默認值,但它不適用於矢量 –

3

除了@ToniVanhanla's answer,對於JVM,相關的Clojure接口是clojure.lang.ILookup

看,就像美國人說,在引擎蓋下,

  • Clojure的get轉化到clojure.lang.RT/get通話。
  • 如果可能,這會投射到ILookup並調用相應的 valAt方法。
  • 如果不是,它會調用...RT/getFrom
  • ...它的條款涉及明確地,反過來,
    • Java的地圖,
    • 的Clojure集和
    • Java字符串和數組。

如果沒有這些擬合的,它返回nil

Java數組沒有父接口:它們都直接從Object下降。他們是由Java的Class/isArray


出人意料的是,Clojure的get不會對Java集合的工作,如Vector小號檢測:

(java.util.Vector. (seq "Hello, world!")) 
=> [\H \e \l \l \o \, \space \w \o \r \l \d \!] 

(get (java.util.Vector. (seq "Hello, world!")) 4) 
=> nil 
相關問題