Last active
December 16, 2015 15:58
-
-
Save minhnhdo/5459316 to your computer and use it in GitHub Desktop.
Set operations in Common Lisp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defun powerset (list) | |
"powerset returns the list of sublists of list" | |
(reduce #'(lambda (e l) | |
(nconc (mapcar #'(lambda (l) (cons e l)) l) | |
l)) | |
list | |
:from-end t | |
:initial-value '(nil))) | |
(defun permutation (list) | |
"permutation returns a list of permutations of list" | |
(labels ((helper (acc front el back end-p) | |
(if end-p | |
acc | |
(let ((permu (permutation (append front back)))) | |
(helper (nconc acc | |
(mapcar #'(lambda (l) (cons el l)) permu)) | |
(nconc front (list el)) | |
(car back) | |
(cdr back) | |
(null back)))))) | |
(if (or (null list) (null (cdr list))) | |
(list list) | |
(helper () () (car list) (cdr list) nil)))) | |
(defun combination (list k) | |
"combination returns a list of k-combinations of list" | |
(delete-if-not | |
#'(lambda (l) (= (length l) k)) | |
(reduce #'(lambda (e acc) | |
(delete-if-not #'(lambda (e) (<= (length e) k)) | |
(nconc (mapcar #'(lambda (acc) (cons e acc)) acc) | |
acc))) | |
list | |
:from-end t | |
:initial-value '(nil)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment