From: Niels Giesen <niels.giesen@gmail.com>
To: help-gnu-emacs@gnu.org
Subject: Re: How could I modify list element?
Date: Tue, 09 Dec 2008 21:46:53 +0100 [thread overview]
Message-ID: <87r64hqdoi.fsf@gmail.com> (raw)
In-Reply-To: mailman.2319.1228836378.26697.help-gnu-emacs@gnu.org
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)))))
next prev parent reply other threads:[~2008-12-09 20:46 UTC|newest]
Thread overview: 8+ messages / expand[flat|nested] mbox.gz Atom feed top
[not found] <mailman.2319.1228836378.26697.help-gnu-emacs@gnu.org>
2008-12-09 16:36 ` How could I modify list element? Andreas Politz
2008-12-09 20:46 ` Niels Giesen [this message]
2008-12-09 14:15 richardeng
2008-12-09 15:37 ` Alan Mackenzie
2008-12-09 17:43 ` richardeng
[not found] ` <mailman.2345.1228845668.26697.help-gnu-emacs@gnu.org>
2008-12-09 20:30 ` Andreas Politz
2008-12-09 17:21 ` Thierry Volpiatto
2008-12-09 17:26 ` Thierry Volpiatto
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
List information: https://www.gnu.org/software/emacs/
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=87r64hqdoi.fsf@gmail.com \
--to=niels.giesen@gmail.com \
--cc=help-gnu-emacs@gnu.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).