在列表的第 N 个位置插入一个新元素
Insert a new element at the N-th position of a list
是否可以在没有conj的情况下在列表的第N个位置插入一个新元素?
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)))))
使用 split-at 并在列表的两半之间插入新元素:
(defn list-insert [lst elem index]
(let [[l r] (split-at index lst)]
(concat l [elem] r)))
示例:
(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)
是否可以在没有conj的情况下在列表的第N个位置插入一个新元素?
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)))))
使用 split-at 并在列表的两半之间插入新元素:
(defn list-insert [lst elem index]
(let [[l r] (split-at index lst)]
(concat l [elem] r)))
示例:
(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)