你没有说如果你想要remove
功能或delete
功能。我会在这里做非破坏性的版本。
您可以制作一个列表的remove-nth
,方法是在索引之前创建所有元素的新列表,然后使用要删除的cons
的尾部以共享尽可能多的结构。这是一个使用subseq
,nconc
和nthcdr
的实现来展示它是多么容易,没有递归。
(defun remove-nth (n list)
(nconc (subseq list 0 n) (nthcdr (1+ n) list)))
(defparameter *test* (list 0 1 2 3 4 5 6))
(remove-nth 3 *test*) ; ==> (0 1 2 4 5 6)
(remove-nth 0 *test*) ; ==> (1 2 3 4 5 6)
递归函数会是这个样子:
(defun remove-nth-rec (n list)
(assert (not (null list)))
(if (zerop <??>)
<??>
(cons <??> (remove-nth-rec <??> <??>))))
可以使功能,这是否对每个子表递归了。我会用mapcar
做到这一点:
(defun remove-all-nth (n lol)
(mapcar (lambda (x) (remove-nth n x)) lol))
(remove-all-nth 0 '((a b c) (0 1 2) (I II III))) ; ==> ((b c) (1 2) (II III))
递归函数会是这个样子:
(defun remove-all-nth-rec (n list)
(if (null <??>)
nil
(cons (remove-nth-rec n <??>)
(remove-all-nth-rec n <??>))))