Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. (defun rotate-list (list)
  2. (cond
  3. ((endp list)) ; 0 elements
  4. ((endp (rest list))) ; 1 element
  5. ((endp (rest (rest list))) ; 2 elements
  6. (rotatef (car list) (cadr list)))
  7. ((endp (rest (rest (rest list)))) ; 3 elements
  8. (rotatef (car list) (cadr list) (caddr list)))
  9. (t
  10.  
  11. ;; Principle:
  12. ;; 1- the first and last cons are not moved, their car are updated.
  13. ;; 2- the second cons is moved to the before last cons position.
  14. ;; 3- the other conses are not changed.
  15.  
  16. ;; (a . (b . (c . (d … . (e . (f . nil))))))
  17. ;; (a . (c . (d … . (e . (b . (f . nil))))))
  18.  
  19. (rotatef (car (last list))
  20. (car list)
  21. (car (cdr list)))
  22. (rotatef (cdr (last list 2))
  23. (cdr list)
  24. (cdr (cdr list)))))
  25. list)
  26.  
  27.  
  28. (dolist (test '(()
  29. (1)
  30. (1 2)
  31. (1 2 3)
  32. (1 2 3 4)
  33. (1 2 3 4 5)
  34. (1 2 3 4 5 6)))
  35.  
  36. (let ((test (copy-list test)))
  37. (print (rotate-list test))))
  38.  
  39. nil
  40. (1)
  41. (2 1)
  42. (2 3 1)
  43. (2 3 4 1)
  44. (2 3 4 5 1)
  45. (2 3 4 5 6 1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement