[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[elpa] externals/dash 1120417 127/439: Add -group-by

From: Phillip Lord
Subject: [elpa] externals/dash 1120417 127/439: Add -group-by
Date: Tue, 04 Aug 2015 20:27:08 +0000

branch: externals/dash
commit 1120417d5314452a30cb6085525dbb8c2be7d943
Author: Takafumi Arakaki <address@hidden>
Commit: Takafumi Arakaki <address@hidden>

    Add -group-by
 dash.el |   32 ++++++++++++++++++++++++++++++++
 1 files changed, 32 insertions(+), 0 deletions(-)

diff --git a/dash.el b/dash.el
index 4103eae..a5e40bb 100644
--- a/dash.el
+++ b/dash.el
@@ -405,6 +405,38 @@ The last group may contain less than N items."
   "Applies FN to each value in LIST, splitting it each time FN returns a new 
   (--partition-by (funcall fn it) list))
+(defmacro --group-by (form list)
+  "Anaphoric form of `-group-by'."
+  (let ((l (make-symbol "list"))
+        (v (make-symbol "value"))
+        (k (make-symbol "key"))
+        (r (make-symbol "result")))
+    `(let ((,l ,list)
+           ,r)
+       ;; Convert `list' to an alist and store it in `r'.
+       (while ,l
+         (let* ((,v (car ,l))
+                (it ,v)
+                (,k ,form)
+                (kv (assoc ,k ,r)))
+           (if kv
+               (setcdr kv (cons ,v (cdr kv)))
+             (push (list ,k ,v) ,r))
+           (setq ,l (cdr ,l))))
+       ;; Reverse lists in each group.
+       (let ((rest ,r))
+         (while rest
+           (let ((kv (car rest)))
+             (setcdr kv (nreverse (cdr kv))))
+           (setq rest (cdr rest))))
+       ;; Reverse order of keys.
+       (nreverse ,r))))
+(defun -group-by (fn list)
+  "Separate LIST into an alist whose keys are FN applied to the
+elements of LIST.  Keys are compared by `equal'."
+  (--group-by (funcall fn it) list))
 (defun -interpose (sep list)
   "Returns a new list of all elements in LIST separated by SEP."
   (let (result)

reply via email to

[Prev in Thread] Current Thread [Next in Thread]