Q: how do I rotate the elements of a list such that last becomes first?
Given a list of arbitrary length, how do I rotate the list non-destructively such that the last element becomes the first element?
What doesn't work
cl-rotatef doesn't seem to work for my purposes. First, it
modifies in place (but I could deal with that). Second, it
spits up when I use
last (apparently, they're not
(let ((list '(a b c))) (cl-rotatef (butlast list) (last list)))
gives the error message
Symbol's function definition is void: (setf butlast)
What works, but seems inefficient
Here's what I've got:
(let ((list '(a b c))) (let ((rev (reverse list))) (cons (pop rev) (nreverse rev)))) ; => (c a b)
This snippet works as expected. However, it seems inefficient in
reverses at the front and then
nreverses at the back.
I'm only using this function on short lists (3 or 4 elements at most), so it's not such a big deal in practice. But I'd still like to know how to rotate efficiently. (If there's a built-in function to do this that I've missed, even better.)