I've a question, how to return a list without the nth element of a given list? E.g., given list: (1 2 3 2 4 6)
, and given n = 4
, in this case the return list should be (1 2 3 4 6)
.
A simple recursive solution:
(defun remove-nth (n list)
(declare
(type (integer 0) n)
(type list list))
(if (or (zerop n) (null list))
(cdr list)
(cons (car list) (remove-nth (1- n) (cdr list)))))
This will share the common tail, except in the case where the list has n
or more elements, in which case it returns a new list with the same elements as the provided one.
Using remove-if
:
(defun foo (n list)
(remove-if (constantly t) list :start (1- n) :count 1))
butlast
/nthcdr
solution (corrected):
(defun foo (n list)
(append (butlast list (1+ (- (length list) n))) (nthcdr n list)))
Or, maybe more readable:
(defun foo (n list)
(append (subseq list 0 (1- n)) (nthcdr n list)))
Using loop
:
(defun foo (n list)
(loop for elt in list
for i from 1
unless (= i n) collect elt))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With