Search code examples
clojure

Insert a new element at the N-th position of a list


Is it possible to insert a new element at the N-th position of a list without conj?

defn insert-at [x xs n]
  (let [[before after] (my-drop xs (dec n))]
    (if (empty? after)
      (if (= (count before) (dec n))
        (concat before (replicate 1 x))
        before)
      (concat before (conj after x)))))

Solution

  • Use split-at and insert new element between two halves of list:

    (defn list-insert [lst elem index]
      (let [[l r] (split-at index lst)]
        (concat l [elem] r)))
    

    Examples:

    (list-insert '(1 2 3 4 5) 0 0)
    => (0 1 2 3 4 5)
    (list-insert '(1 2 3 4 5) 1 1)
    => (1 1 2 3 4 5)