help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Setting the nth element of a list


From: Nordlöw
Subject: Re: Setting the nth element of a list
Date: Fri, 5 Jun 2009 06:10:06 -0700 (PDT)
User-agent: G2/1.0

On Jun 5, 3:06 pm, Nordlöw <per.nord...@gmail.com> wrote:
> On Jun 5, 4:25 am, Barry Margolin <bar...@alum.mit.edu> wrote:
>
>
>
> > In article
> > <8a7c4d36-195d-4517-827e-7fbeca7ae...@r34g2000vba.googlegroups.com>,
>
> >  Nordlöw <per.nord...@gmail.com> wrote:
> > > This simple example changes the second element in the list x:
>
> > > (setq x '(a nil c))
> > > (setcar (cdr x 'b)
>
> > > How do I generalize this to a function that sets (changes) the nth
> > > element of a list (for side effects only)?
>
> > > Thanks in advance,
> > > Nordlöw
>
> > (require 'cl-macs)
> > (setf (nth n x) 'b)
>
> > --
> > Barry Margolin, bar...@alum.mit.edu
> > Arlington, MA
> > *** PLEASE post questions in newsgroups, not directly to me ***
> > *** PLEASE don't copy me on replies, I'll read them in the group ***
>
> Okey, here is my solution:
>
> (defun setnthcar (n list x)
>   "Set N:th element of LIST to X for side effects only."
>   (setcar (nthcdr n list) x))
>
> Comments on that?
>
> How do I accomplish the same with arrays? Using aref I guess. Here is
> my mockup that doesn't yet do what I want:
>
> (defun setnthref (n array x)
>   "Set N:th element of ARRAY to X for side effects only."
>   (set (aref array n) x))
>
> Thanks in advance,
> Nordlöw

Okey I found a solution:

(defun setnthref (n array x)
  "Set N:th element of ARRAY to X for side effects only."
  (setf (aref array n) x))
;; (equal (let ((l '[a b c])) (setnthref 1 l 'B) l) '[a B c])

Is this the most efficient way? I see that setf() is quite
complicated.

/Nordlöw


reply via email to

[Prev in Thread] Current Thread [Next in Thread]