XD::LIST:INSERT-NTH
;; ------------------------------------------------------------------------
;;; 函数名称 / Function Name: XD::LIST:INSERT-NTH
;;;
;;; 【功能说明 / Description】
;;; 在列表 lst 的第 n 个位置插入元素 a,返回插入后的新列表。
;;; 索引从 0 开始计数。
;;;
;;; 【参数说明 / Parameters】
;;; a - (any) 要插入的元素
;;; lst - (list) 原始列表
;;; n - (integer) 插入位置索引(从0开始)
;;;
;;; 【返回值 / Return Value】
;;; (list) 插入元素后的新列表
;;;
;;; 【依赖函数 / Dependencies】
;;; - nth : 访问列表中指定索引的元素
;;; - length : 获取列表长度
;;; - cons : 构造列表
;;; - reverse: 反转列表
;;; - repeat : 重复执行代码块
;;;
;;; 【备注 / Notes】
;;; - 如果 n 大于列表长度,则相当于在列表末尾插入元素。
;;; - 该函数通过两次遍历原列表,构造新列表。
;;;
(defun XD::LIST:INSERT-NTH (a lst n / lst2 j)
(setq j 0)
(setq lst2 nil)
;; 复制 lst 的前 n 个元素到 lst2
(repeat n
(setq lst2 (cons (nth j lst) lst2))
(setq j (+ j 1))
)
;; 插入元素 a
(setq lst2 (cons a lst2))
;; 复制 lst 剩余元素到 lst2
(repeat (- (length lst) n)
(setq lst2 (cons (nth j lst) lst2))
(setq j (+ j 1))
)
;; 反转 lst2 得到正确顺序的新列表
(reverse lst2)
)
:o:'(:time:
页:
[1]