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"
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/
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)