2014-10-18 142 views
2

我創建了一個名爲pretend的地圖列表。Clojure:將列表中的元素插入特定索引處的矢量

(def pretend (map (fn [num] {:alias (str "alias " num), :real (str "real " num)}) (range 6 32))) 

其中給出:

({:alias "alias 6", :real "real 6"} {:alias "alias 7", :real "real 7"} {:alias "alias 8", :real "real 8"} {:alias "alias 9", :real "real 9"} {:alias "alias 10", :real "real 10"} {:alias "alias 11", :real "real 11"} {:alias "alias 12", :real "real 12"} {:alias "alias 13", :real "real 13"} {:alias "alias 14", :real "real 14"} {:alias "alias 15", :real "real 15"} {:alias "alias 16", :real "real 16"} {:alias "alias 17", :real "real 17"} {:alias "alias 18", :real "real 18"} {:alias "alias 19", :real "real 19"} {:alias "alias 20", :real "real 20"} {:alias "alias 21", :real "real 21"} {:alias "alias 22", :real "real 22"} {:alias "alias 23", :real "real 23"} {:alias "alias 24", :real "real 24"} {:alias "alias 25", :real "real 25"} {:alias "alias 26", :real "real 26"} {:alias "alias 27", :real "real 27"} {:alias "alias 28", :real "real 28"} {:alias "alias 29", :real "real 29"} {:alias "alias 30", :real "real 30"} {:alias "alias 31", :real "real 31"}) 

而且我希望到列表中的每個元素插入下面的載體。

(def identities 
    [{:alias "Batman" :real "Bruce Wayne"} 
    {:alias "Spiderman" :real "Peter Parker"} 
    {:alias "Santa" :real "Your mom"} 
    {:alias "Easter Bunny" :real "Your dad"} 
    {:alias "alias 5", :real "real 5"} 
    ;; ... elements from the "pretend" list should be inserted here 
    {:alias "alias 31", :real "real 31"} 
    {:alias "alias 32", :real "real 32"} 
    {:alias "alias 33", :real "real 33"} 
    {:alias "alias 34", :real "real 34"}]) 

但我沒有這樣做,當我嘗試以下。它將索引5中的元素替換爲地圖列表,這不是我想要的。我想從列表pretend插入地圖中的所有元素到地圖的矢量在索引5

(def identities (assoc identities 5 pretend)) 

回答

5
(let [[before after] (split-at 5 identities)] 
    (vec (concat before pretend after))) 

我對你的數據結構兩方面的關注。

  • 您正在使用def進行增量更改。做兩遍,並且 你會有一堆重複的條目。
  • 你需要一個載體的地圖?如果一個別名只有一個真實的身份,那麼你可以有一個從別名到真實身份的映射。

它看起來像這樣:

(into {} (map (juxt :alias :real) identities)) 

{"Batman" "Bruce Wayne", "alias 5" "real 5", "Santa" "Your mom", 
"alias 31" "real 31", "alias 32" "real 32", "alias 33" "real 33", 
"Easter Bunny" "Your dad", "alias 34" "real 34", "Spiderman" "Peter Parker"} 

您可以從您的identities從而得出它

相關問題