Zach Beane (xach) wrote,

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.

Tags: lisp
  • Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded  

  • 0 comments