TheSwamp
Code Red => AutoLISP (Vanilla / Visual) => Topic started by: Mark on February 02, 2004, 12:07:30 PM
-
I need to remove the nth item from a list. What the item is does not matter just the position of the item in the list. Make sense?
Example:
(setq lst '(1 2 3 6 7 8))
(1 2 3 6 7 8)
Now remove the 4th item leaving me with this;
(1 2 3 7 8)
-
(defun listItem:Remove (e l)
(apply 'append (subst nil (list(nth e l))(mapcar 'list l)))
)
Concept borrowed from Matt ...
Thanks Matt .. :wink:
-
- Keith
That removes all the items matching 'e' I want to remove just the nth item from the list.
-
So, none of the lisps that were submitted as part of Se7en's challenge work quite right?
-
nope, unless I'm missing something.
-
Removing the nth item from a list (untested):
(defun rnth (l i / c e)
;; l = list
;; i = index (0-based)
(setq c 0)
(while (setq e (nth c l))
(if (/= i c) (setq rl (cons e rl))
(setq c (1+ c))
)
(reverse rl)
)
(rnth '(0 1 2 3 4) 3) -> '(0 1 2 4)
-
Mark, as far I can see all these from Se7en's challenge worked:
;; nthRemove challenge by Se7en, jan. 2004
;; Keith:
(defun NthRemover ( ndx lst / count newlist )
(setq count 0)
(repeat (length lst)
(if (/= count ndx)
(setq newlist (append newlist (list (car lst))))
)
(setq lst (cdr lst)
count (1+ count)
)
)
newlist
)
;; Keith:
;; Only removing if unique value to be removed!
(defun nthremove ( ndx lst )
(append
(reverse (cdr (member (nth ndx lst) (reverse lst))))
(cdr (member (nth ndx lst) lst))
)
)
;; Kerry B:
(defun nthremover_2 (lst i / tmp)
(if (and i (vl-consp lst) (not (minusp i)))
(progn (repeat (min i (length lst))
(setq tmp (cons (car lst) tmp)
lst (cdr lst)
)
)
(append (reverse tmp) (cdr lst))
)
lst
)
)
;; SMadsen:
(defun removeNth (lst i / a)
(setq a -1)
(vl-remove-if (function (lambda (n)(= (setq a (1+ a)) i))) lst)
)
;; SMadsen:
(defun nthRemove_2 (lst i)
(and (atom i)(setq i (cons 0 i)))
(cond ((null lst) nil)
((= (car i) (cdr i))(nthRemove_2 (cdr lst) (cons (1+ (car i)) (cdr i))))
((cons (car lst) (nthRemove_2 (cdr lst) (cons (1+ (car i)) (cdr i)))))
)
)
;; SMadsen:
(defun removeNth_2 (lst i / a b)
(cond ((>= i (length lst)) lst)
((setq a lst b (reverse lst))
(append (reverse (repeat (- (length b) i) (setq b (cdr b))))
(repeat (1+ i) (setq a (cdr a))))
)
)
)
;; Se7en:
(defun nthRemover_3 (lst item / nlst cntr)
(defun Nested-nthRemover (lst item)
(if (/= (if (not cntr)
(setq cntr 0)
cntr
)
item
)
(setq nlst (cons (car lst) nlst))
)
(setq cntr (1+ cntr))
(if (> (length (cdr lst)) 0)
(Nested-nthRemover (cdr lst) item)
(setq cntr nil)
)
(reverse nlst)
)
(Nested-nthRemover lst item)
)
-
My apologies, some of those do work.
-
My apologies, some of those do work.
I would encourage the use of (cons) and a (reverse) instead of (append) for creating lists.
-
Just became aware that acadx.com (http://code.acadx.com) also has a removeNth function available. Merely a variation of some of the above, though.