;;; Function that returns all possible choices of K elements from a ;;; given list L. Solution courtesy of Martin Buchmann, with cosmetic ;;; editions by JM. (defun combination (k l) (cond ((< k 0) nil) ((= k 0) (list nil)) ((> k (length l)) nil) (t (append (mapcar #'(lambda (x) (cons (first l) x)) (combination (1- k) (rest l))) (combination k (rest l)) ) ) ) ) ;;; Alternative solution sent to me by Wojciech Gac on 2014-01-17 ;;; Just indentation editing by JM. (defun combination (n lst) (cond ((zerop n) nil) ((= n 1) (mapcar #'list lst)) (t (mapcan #'(lambda (x) (mapcar #'(lambda (y) (append (list x) y)) (combination (1- n) (setf lst (delete x lst))))) lst)) ) )