Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update an item in a vector in Clojure?

Tags:

If I have a Vector:

[1 2 3 4 5 6 7 8 9]

: and I want to replace the 5 with a 0 to give:

[1 2 3 4 0 6 7 8 9]

How can I do this when I only know the index as being 4?

Something like:

 (replace-in-vec [1 2 3 4 5 6 7 8 9] 4 0)
like image 976
yazz.com Avatar asked May 29 '11 14:05

yazz.com


1 Answers

assoc works with vectors too!

 Usage: (assoc map key val)
        (assoc map key val & kvs)

assoc[iate]. When applied to a map, returns a new map of the same (hashed/sorted) type, that contains the mapping of key(s) to val(s). When applied to a vector, returns a new vector that contains val at index. Note - index must be <= (count vector).

(assoc [1 2 3] 1 :a)
 => [1 :a 3]
like image 169
mike3996 Avatar answered Sep 17 '22 15:09

mike3996