Log in

Permutation and list rotation

Here's an interesting implementation of a list permutation function, by Erik Naggum:

(defun permutations (list)
  (if (cdr list)
      (loop with rotation = list
          do (setq rotation (nconc (last rotation) (nbutlast rotation)))
          nconc (loop for list in (permutations (rest rotation))
                      collect (cons (first rotation) (copy-list list)))
          until (eq rotation list))
      (list list)))

The rotation trick with nconc/last/nbutlast/eq is new to me.