2015-10-16 58 views
1

我:如何從defrecord創建一個集合?

(defrecord human-being [uuid first-name last-name genome-sequence]) 

(defrecord space-ship [uuid ship-type engines home-world captain]) 

我希望有一個單一的「建築」功能,將採取任何人的福利或空艦的記錄,並用鑰匙作爲實際記錄鍵返回一組:

(def john (human-being. "ABC123" "John" "Smith" "QWERTY")) 
(def enterprise (space-ship. "ZXC123" "Galactic" "Warp" "Earth" "Picard")) 

(constructFunc john) --returns--> {:uuid "ABC123" :first-name "John" :last-name "Smith" :genome-sequence "QWERTY"} 

(constructFunc enterprise) --returns--> {:uuid "ZXC123" :ship-type "Galactic" :engines "Warp" :home-world "Earth" :captain "Picard"} 

我不只是想要這兩個defrecords。我需要能夠將降大任於defrecords並獲得類似的輸出...

我有我應該使用這個宏的感覺,但讓我害怕有點....

+0

我不確定我明白,「我不只是想要這兩個defrecords」,所以你想要一個集合中的地圖? (進入(哈希集)(地圖#(到{}%)[約翰企業]))''也許? – birdspider

+0

所以我想有一個通用的函數,我可以放棄任何類型的defrecord(也許還沒有定義),它只是吐出一張地圖...... – Zuriar

+0

'#(into {}%)'這樣做(或者如果你更喜歡一個名爲fn'(defn - > map [r](into {} r))') – birdspider

回答

1

看到的問題是essantialy「我怎麼把Defrecord變成地圖」我可以想到4種或多或少的等價方法。

; direct - but this is stricly speaking not 'a function' 
(into {} john) 

; anonymous 
(#(into {} %) john) 

; named 
(defn ->map [r] 
    (into {} r)) 
(->map john) 

; via composition/partial 
((partial into {}) john)  

; all of them return 
{:uuid "ABC123", :first-name "John", :last-name "Smith", :genome-sequence "QWERTY"} 
+0

非常感謝,太簡單了!有沒有辦法讓defrecord的'type'成爲一個字符串......例如:(typeOfRecord enterprise)--->「space-ship」? – Zuriar

+0

'(類型約翰)'或類似的 – birdspider