Simple way to replace nth element in a vector in clojure?
VectorClojureVector Problem Overview
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?
Vector Solutions
Solution 1 - Vector
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]
Solution 2 - Vector
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]