Skip to content

Instantly share code, notes, and snippets.

@fukamachi
Created January 5, 2011 15:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fukamachi/766438 to your computer and use it in GitHub Desktop.
Save fukamachi/766438 to your computer and use it in GitHub Desktop.
groupBy for CL
(defun group-by (pred list)
(loop
while list
for cur = (pop list)
collect
(nreverse
(loop with acc = (list cur)
while list
for x = (pop list)
if (funcall pred cur x)
do (push x acc)
else do (progn (push x list)
(return acc))
finally (return acc)))))
(group-by #'= '(1 1 2 3 1 1 4))
;;=> ((1 1) (2) (3) (1 1) (4))
(group-by (lambda (x y)
(equal (mod y 3) (mod x 3)))
'(1 1 2 3 1 1 4))
;;=> ((1 1) (2) (3) (1 1 4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment