【问题标题】:Insert a new element at the N-th position of a list在列表的第 N 个位置插入一个新元素
【发布时间】:2021-11-09 19:50:46
【问题描述】:

是否可以在不使用 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)))))

【问题讨论】:

    标签: clojure


    【解决方案1】:

    使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-15
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      • 2020-12-08
      • 1970-01-01
      • 2020-07-25
      相关资源
      最近更新 更多