Return plain map from a Clojure record

后端 未结 3 1530
渐次进展
渐次进展 2021-01-19 21:54

I have a record:

(defrecord Point [x y])
(def p (Point. 1 2))

Now I want to extract just the map from the record. These ways get the job do

3条回答
  •  死守一世寂寞
    2021-01-19 22:02

    A. Webb suggested the much-simpler (into {} p) in the comments. Thanks!

    Here is a code snippet that is more general; it works for recursive records:

    (defrecord Thing [a b])
    (def t1 (Thing. 1 2))
    (def t2 (Thing. 3 4))
    (def t3 (Thing. t1 t2))
    
    (defn record->map
      [record]
      (let [f #(if (record? %) (record->map %) %)
            ks (keys record)
            vs (map f (vals record))]
        (zipmap ks vs)))
    
    (record->map t3)
    ; {:b {:b 4, :a 3}, :a {:b 2, :a 1}}
    

提交回复
热议问题