Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common Lisp: How to return a list without the nth element of a given list?

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).

like image 501
user1232236 Avatar asked Feb 25 '12 14:02

user1232236


2 Answers

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.

like image 176
Samuel Edwin Ward Avatar answered Oct 13 '22 01:10

Samuel Edwin Ward


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))
like image 22
danlei Avatar answered Oct 13 '22 01:10

danlei