Add a permanent vector map to clojure

I am 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") )) 

At the end of the loop, I want the itemList contain 10 objects. Any help really liked

+4
source share
2 answers

Clojure is a functional programming language, and all of its basic data structures are immutable and constant. This also includes a vector.

In your example, you need to manage the state. Clojure provides several abstractions for this, of which, I think, atoms are better for your use.

 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"}]> 
+4
source

missingfaktor answers correctly if you really need to change something, but it would be much more normal:

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

In other words, create a list of objects with content.

+3
source

Source: https://habr.com/ru/post/1415796/


All Articles