2015-10-16 116 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