Last active
January 24, 2016 22:02
-
-
Save StephenWakely/dc013adf87efd8a83b3b to your computer and use it in GitHub Desktop.
Group by 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 group-by (fn coll &key groupfn keyname valuename) | |
"Groups the collection by the results of calling fn on each element. | |
The results of calling groupfn on the elements are grouped together. | |
Returned is a property list of the keyname to valuename properties." | |
(labels ((get-item (item) | |
(if groupfn | |
(funcall groupfn item) | |
item)) | |
(find-plist (grouped keyvalue) | |
(first | |
(remove-if-not (lambda (plist) | |
(equal (getf plist keyname) keyvalue)) | |
grouped))) | |
(group (grouped item) | |
(let ((curr (find-plist grouped (funcall fn item)))) | |
(if curr | |
(progn | |
(setf (getf curr valuename) | |
(cons (get-item item) (getf curr valuename))) | |
grouped) | |
(cons (list keyname (funcall fn item) | |
valuename (list (get-item item))) | |
grouped))))) | |
(reduce #'group coll :initial-value '()))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment