Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a nested vector

Tags:

vector

clojure

Let's say i have the following vector

(def x [[1 2 3] [4 5 6] [7 8]])

and I want to append the number 9 to the last vector (I don't know the index of the vector)

(conj (vec (butlast x)) (conj (last x) 9))
 #=> [[1 2 3] [4 5 6] [7 8 9]]

Is there a better/clearer way to do this?

like image 942
KobbyPemson Avatar asked Aug 05 '14 18:08

KobbyPemson


1 Answers

Use the efficient tail access functions

(conj (pop x) (conj (peek x) 9))

But you could also

(update-in x [(dec (count x))] conj 9)
like image 126
A. Webb Avatar answered Sep 27 '22 19:09

A. Webb