试着学习lisp,想要删除每第n个。我只删除了第一(第n)个元素
(defun delete-nth (n list)
(if (zerop n)
(cdr list)
(let ((cons (nthcdr (1- n) list)))
(if cons
(setf (cdr cons) (cddr cons))
cons))))我想删除下一个第n个,依此类推
我还试过这个:
(defun remove-nth (list n)
(remove-if (constantly t) list :start n :end (+ 1 n)))不知道如何重新开始
我想的是连接,但我不知道如何跟踪我的位置。
发布于 2013-01-10 00:15:24
做同样事情的另一种方法:
(defun remove-all-nth (list period)
(remove-if
(let ((iterator 0))
(lambda (x)
(declare (ignore x))
(= 0 (mod (incf iterator) period)))) list))
(remove-all-nth '(1 2 3 4 5 6 7 8 9 0) 3)
; (1 2 4 5 7 8 0)发布于 2013-01-09 23:23:42
从1开始计数(更改为0是微不足道的):
(defun remove-every-nth (n list)
(loop for element in list
for index from 1
unless (zerop (rem index n))
collect element))另外:请正确缩进您的代码。
发布于 2013-01-10 06:36:32
也许这里有一个更具学术色彩的递归解决方案:
(defun delete-nth (n list)
(labels ((rec (i list)
(cond ((null list) nil)
((= i 1) (rec n (cdr list)))
(t (cons (car list) (rec (1- i) (cdr list)))))))
(rec n list)))但在现实生活中,我会使用上面的循环选项。
https://stackoverflow.com/questions/14237514
复制相似问题