From: Nikola Skoric
Subject: [newbie] removing last element of a list
Date: 
Message-ID: <MPG.1eed17e4ac002c159896bb@news.t-com.hr>
Is there a more efficient way to remove the last element of a list than 
(reverse (cdr (reverse x)))? I'm rotating a list, and I did it this way:

(defun rrot (x)
	(append (last x) (reverse (cdr (reverse x)))))

So now I'm wondering if I could do that more efficiently...

-- 
"Now the storm has passed over me
I'm left to drift on a dead calm sea
And watch her forever through the cracks in the beams
Nailed across the doorways of the bedrooms of my dreams" 

From: Pascal Costanza
Subject: Re: [newbie] removing last element of a list
Date: 
Message-ID: <4egd8bF1eu6p9U1@individual.net>
Nikola Skoric wrote:
> Is there a more efficient way to remove the last element of a list than 
> (reverse (cdr (reverse x)))? I'm rotating a list, and I did it this way:
> 
> (defun rrot (x)
> 	(append (last x) (reverse (cdr (reverse x)))))
> 
> So now I'm wondering if I could do that more efficiently...

See butlast and nbutlast.

If you want to do it manually:

(defun rrot (x)
   (when x
     (loop for (elm . rest) on x
           if rest collect elm into result
           else return (cons elm result))))


Pascal

-- 
3rd European Lisp Workshop
July 3 - Nantes, France - co-located with ECOOP 2006
http://lisp-ecoop06.bknr.net/
From: Steven M. Haflich
Subject: Re: [newbie] removing last element of a list
Date: 
Message-ID: <1MPgg.46150$Lm5.45388@newssvr12.news.prodigy.com>
Pascal Costanza wrote:
> Nikola Skoric wrote:
>> Is there a more efficient way to remove the last element of a list 
>> than (reverse (cdr (reverse x)))? I'm rotating a list, and I did it 
>> this way:
> See butlast and nbutlast.

But beware the exceptional case where the second argument to nbutlast is
equal to the length of the list.

cl-user(8): (let ((list (list 1 2)))
	      (nbutlast list 1)
	      list)
(1)
cl-user(9): (let ((list (list 1 2)))
	      (nbutlast list 2)
	      list)
(1 2)