git.fiddlerwoaroof.com
Browse code

feat(group-by): add group-by function

Edward Langley authored on 30/03/2022 04:10:08
Showing 1 changed files
... ...
@@ -323,6 +323,20 @@
323 323
                           it
324 324
                           (alexandria:iota it-length))))))))
325 325
 
326
+(defun-ct group-by (fn &key (test 'equal))
327
+  (lambda (seq)
328
+    (let ((groups (make-hash-table :test test)))
329
+      (map nil
330
+           (lambda (it)
331
+             (push it
332
+                   (gethash (funcall fn it)
333
+                            groups)))
334
+           seq)
335
+      (mapcar (lambda (it)
336
+                (cons (car it)
337
+                      (reverse (cdr it))))
338
+              (alexandria:hash-table-alist groups)))))
339
+
326 340
 #+nil
327 341
 (defmacro <> (arity &rest funs)
328 342
   (let ((arg-syms (loop repeat arity collect (gensym))))