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

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

Re: Appending lists


From: tomas
Subject: Re: Appending lists
Date: Tue, 15 Jun 2021 11:18:34 +0200
User-agent: Mutt/1.5.21 (2010-09-15)

On Tue, Jun 15, 2021 at 10:27:48AM +0200, Emanuel Berg via Users list for the 
GNU Emacs text editor wrote:
> > Also check out `nconc'
> >
> > (nconc '(1 2 3) '(4 5) '(6)) ; (1 2 3 4 5 6) - if this works for you, use it
> > (nconc '(1 2 3) '(4 5)   6 ) ; (1 2 3 4 5 . 6) - see, last "list" isn't a 
> > list!
> >
> > There was a trick with nconc, you could reverse a list in
> > constant time, right? I think that was it but that's all
> > I remember.
> 
> Probably that wasn't `nconc' but `nreverse', I think!
> 
>   (nreverse '(flip six three hole)) ; (hole three six flip)
> 
> Yeah, and it didn't take very long either...
> 
> Here it says
> 
>   Don't use nreverse on quoted list literals; it is undefined
>   behavior and may behave in surprising ways, since it is
>   de facto self-modifying code. [1]

Thing is, '(flip six three hole) is a "constant". It is known
at compile time. The compiler takes its freedom to assume
that it won't be changed. It even might end up in a chunk
of read-only memory if/when the code makes it to a dumped
image. Good luck flipping pointers in cons cells in read-only
memory :)

I'd go even further with the warning: when using nreverse
(and friends), make sure there are no other users of (part
of) your data or be prepared for fun surprises:.

  setq thing (copy-sequence '(one two three four five six)))
  (setq thang (cddr thing))
  
  thang
  => (three four five six)
  
  (nreverse thing)
  => (six five four three two one)
  
  thing
  => (one)
  ; the above isn't the surprise I was after, just a reminder to do
  ; (setq thing (nreverse thing)) -- nreverse won't change your variable
  ; in-place! The result seems weird, but do your box-and-pointer
  ; homework, and you'll get it.
  
  thang
  => (three two one)
  ; now this is what I was after. Who the heck "changed my variable!?"
  ; Who is General Failure and why is he reading my disk?


Hours of fun. Especially when debugging some more involved code :)

Cheers
 - t

Attachment: signature.asc
Description: Digital signature


reply via email to

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