Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: insert elements from a list into a vector at a particular index

Tags:

clojure

I created a list of maps called pretend.

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

Which gives:

({: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"})

And I want to insert each element of the list into the following vector.

(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"}])

But I failed to do so, when I tried the following. It replaced the element at index 5 with a list of maps, which is not what I want. I want to insert all the elements of maps from the list pretend into the vector of maps at index 5.

(def identities (assoc identities 5 pretend))
like image 758
mynameisJEFF Avatar asked Dec 26 '22 03:12

mynameisJEFF


1 Answers

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

I have two concerns about your data structure.

  • You are using def to make an incremental change. Do it twice and you'll have a pile of duplicate entries.
  • Do you need a vector of maps? If an alias has only one real identity, then you can have one map from alias to real identity.

It looks like this:

{"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"}

You can derive it from your identities thus:

(into {} (map (juxt :alias :real) identities))
like image 53
Thumbnail Avatar answered May 12 '23 12:05

Thumbnail