The less-familiar parts of Lisp for beginners — rotatef

Another somewhat obscure feature of Lisp is rotatef.  The rotatef function takes as its arguments a set of places (variables or forms that can be assigned to with setf, think l-value from C++).  It then rotates them, so that the value of the second is moved to the first place, the value of the third moved to the second, and so on, with the value of the first place being moved to the last place.

Calling
*slime-repl sbcl*

CL-USER> (rotatef place1 place2 place3)

is almost like calling
*slime-repl sbcl*
CL-USER> (psetf place1 place2
                place2 place3
                place3 place1)

with the caveat that the psetf example will evaluate each place twice, so if there are side-effects, the behaviour may not be as expected.

Finally, here is an example of using rotatef on places:
*slime-repl sbcl*

CL-USER> (let ((list1 (list 1 2 3 4))
               (list2 (list :A :B :C :D))
               (list3 (list "a" "b" "c" "d")))
           (rotatef (cdr list1) (cdr list2) (cdr list3))
           (values list1 list2 list3))
(1 :B :C :D)
(:A "b" "c" "d")
("a" 2 3 4)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.