Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to replace nth element in a vector in clojure?

Tags:

vector

clojure

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?

like image 695
wrongusername Avatar asked Sep 27 '12 18:09

wrongusername


1 Answers

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]
like image 189
yves Baumes Avatar answered Nov 17 '22 08:11

yves Baumes