2

请看下面的代码:

(def data {:color ["R", "B", "G"] :name "Hello" :up "down"})

(defn collapse-vector-kvp [k v] 
   (map #(hash-map k %) v))

(defn collapse-map [m]
   (map #(let 
      [x %] 
      (if (vector? (val x)) 
            (collapse-vector-kvp (key x) (val x))
            (hash-map (key x) (val x))
        )) m))

(collapse-map data)

=> ({:name "Hello"} ({:color "R"} {:color "B"} {:color "G"}) {:up "down"})

我想做的是创建一个列表,而不是将“颜色”条目放在列表中的列表中。这很容易实现吗?

4

2 回答 2

6
user=> (def data2 '({:name "Hello"} ({:color "R"} {:color "B"} {:color "G"}) {:up "down"}))
#'user/data2
user=> (flatten data2)
({:name "Hello"} {:color "R"} {:color "B"} {:color "G"} {:up "down"})
于 2013-01-11T08:41:32.297 回答
2

另一个版本collapse-map

(defn collapse-map [m]
  (let [sep-m (group-by (comp vector? val) m)]
    (concat (map (fn [[k v]] {k v}) 
                 (sep-m false))
            (apply concat (map (fn [[k v]] 
                                 (collapse-vector-kvp k v)) 
                               (sep-m true))))))

(def test-data {:color ["R" "B" "G"] 
                :name "Hello" 
                :k ["v1" "v2" "v3"] 
                :up "down"})

(collapse-map test-data)
=> ({:name "Hello"}
    {:up "down"}
    {:color "R"}
    {:color "B"}
    {:color "G"}
    {:k "v1"}
    {:k "v2"}
    {:k "v3"})
于 2013-01-11T09:15:45.297 回答