4
votes

I'm trying to figure out a way to add an object to a vector map.

(defstruct item :name)
(def itemList [])

(defn add-item [db & item] 
  (into db item))

(defn get-records[]
  (doseq [i (range 0 10 1)]  
   (add-records itemList  (struct item "test")
  ))

In the end of the loop I want itemList to contain 10 objects. Any help would very much appriciated

2

2 Answers

4
votes

Clojure is a functional programming language and all of its main data structures are immutable and persistent. That also includes vector.

Your example needs managing a state. Clojure provides several abstractions for this, out of which, I think atoms fit your use case best.

user=> (defrecord Item [name])
user.Item

user=> (def item-list (atom []))
#'user/item-list

user=> (defn add-item [db i] (swap! db #(conj % i)))
#'user/add-item

user=> (defn put-records [] 
         (doseq [i (range 10)] 
           (add-item item-list (Item. "test"))))
#'user/put-records

user=> (put-records)
nil

user=> item-list
#<Atom@4204: [#user.Item{:name "test"} #user.Item{:name "test"} #user.Item{:name "test"} #user.Item{:name "test"} #user.Item{:name "test"} #user.Item{:name "test"} #user.Item{:name "test"} #user.Item{:name "test"} #user.Item{:name "test"} #user.Item{:name "test"}]>
3
votes

missingfaktor's answer is right, if you really need to mutate something, but it would be much more normal to have:

(defstruct item :name)
(def itemList (for [i (range 10)] (struct item "test")))

in other words - create the list of objects with the contents.