As a newbie to Clojure, I often have difficulty expressing the simplest things. For example, to replace the last element in a vector that would be
v[-1]=new_value
in python, I get the following options in Clojure:
(assoc v (dec (count v)) new_value)
which is quite long and expressionless, at least, or
(conj (vec (butlast v)) new_value)
worse, since it has an O(n) .
It makes me feel stupid, like a caveman trying to restore a Swiss watch with a club.
What is the correct way for Clojure to replace the last element in a vector?
To support my O(n) class for butlast -version (Clojure 1.8):
(def v (vec (range 1e6))) #'user/v user=> (time (first (conj (vec (butlast v)) 55))) "Elapsed time: 232.686159 msecs" 0 (def v (vec (range 1e7))) #'user/v user=> (time (first (conj (vec (butlast v)) 55))) "Elapsed time: 2423.828127 msecs" 0
Thus, basically over 10 times the number of elements is 10 times slower.
clojure
ead
source share