Search code examples
clojureclojure-contrib

Appending an element at nth index


I'm working on a function, which takes a vector (possibly nested vector) as input along with some quantity y and index n. Essentially the function would append y after the nth element in the vector and adjoin the remaining elements. So far I have the following written, which isn't not working as planned:

(defn funcs [x y n]
(concat (take (- n 1) x) (concat (take-last (- (count x) n) y))))

Solution

  • If you want to return a vector as the final value, you'll have to concatenate your vectors using into (in time linear in the size of the right operand) or core.rrb-vector's catvec (logarithmic time, but the resulting vector will be somewhat slower overall).

    As for the actual implementation, assuming you want to go with core.rrb-vector:

    (require '[clojure.core.rrb-vector :as fv])
    
    (defn append-after-nth [x y n]
      (fv/catvec (fv/subvec x 0 n) y (fv/subvec x n)))