[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How could I modify list element?
From: |
Niels Giesen |
Subject: |
Re: How could I modify list element? |
Date: |
Tue, 09 Dec 2008 21:46:53 +0100 |
User-agent: |
Gnus/5.11 (Gnus v5.11) Emacs/22.1 (gnu/linux) |
richardeng <richardeng@foxmail.com> writes:
> Hi all,
> setcar/setcdr is not convenient.
> In a long list, ex.
> (setq a '(a b c d e f g))
> I want to change 'e to 'E.
> I need a function: (set-list-elt list old-elt new-elt)
>
> How? translate list to vector, modify, then turn it back???
Numerous ways, first the destructive ones:
(setcar (member 'e a) 'E)
(setcar (nthcdr 4 a) 'E)
If (require 'cl) is no problem for you, nth is setfable
(setf (nth 4 a) 'E)
A DIY recursive function can do it too:
(defun set-nth (n list new)
(cond
((or (< n 0) (>= n (length list)))
(error "out of bounds"))
((= n 0)
(setcar list new))
(t (cons (car list) (set-nth (1- n) (cdr list) new)))))
... Or a purely functional approach, to leave the original list intact:
(defun replace-nth (n list new)
(cond
((or (< n 0) (>= n (length list)))
(error "out of bounds"))
((= n 0)
(cons new (cdr list)))
(t (cons (car list) (replace-nth (1- n) (cdr list) new)))))