51
votes

E.g., I have a vector [1, 2, 3], and I want to update the second element so that the vector becomes [1, 5, 3]. In other languages, I would just do something like array[1] = 5, but I'm not aware of anything that would allow me to do this easily in Clojure.

Thoughts on how to accomplish this, or on whether I should be using a different data structure?

2

2 Answers

87
votes

assoc works fine for that. It takes the index where to put the new value and return the newly created vector:

Clojure> (assoc [1 2 3] 1 5)
[1 5 3]
-8
votes

Yve's answer doesn't show how to update the original vector.

This does, but as a Clojure noob, I'm not sure it's the best way:

main=> (def ar [1 2 3])
#'main/ar
main=> ar
[1 2 3]
main=> (def ar (assoc ar 1 5))
#'main/ar
main=> ar
[1 5 3]