Skip to content

Instantly share code, notes, and snippets.

@StephenWakely
Last active January 24, 2016 22:02
Show Gist options
  • Save StephenWakely/dc013adf87efd8a83b3b to your computer and use it in GitHub Desktop.
Save StephenWakely/dc013adf87efd8a83b3b to your computer and use it in GitHub Desktop.
Group by in Common Lisp
(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