]> code.delx.au - gnu-emacs/commitdiff
New function seq-sort-by in seq.el
authorNicolas Petton <nicolas@petton.fr>
Tue, 29 Mar 2016 07:19:32 +0000 (09:19 +0200)
committerNicolas Petton <nicolas@petton.fr>
Tue, 29 Mar 2016 07:19:32 +0000 (09:19 +0200)
* lisp/emacs-lisp/seq.el (seq-sort-by): New function.
* test/lisp/emacs-lisp/seq-tests.el: New test for seq-sort-by.
* doc/lispref/sequences.texi: Add documentation for seq-sort-by.

doc/lispref/sequences.texi
lisp/emacs-lisp/seq.el
test/lisp/emacs-lisp/seq-tests.el

index f7d26e54d0bd19449e1337f626387811461329c9..08e5e3ae35c6e6ff15909fc4f78cc1712bb9d415 100644 (file)
@@ -763,6 +763,18 @@ according to @var{function}, a function of two arguments that returns
 non-@code{nil} if the first argument should sort before the second.
 @end defun
 
+@defun seq-sort-by function predicate sequence
+  This function is similar to @code{seq-sort}, but the elements of
+@var{sequence} are transformed by applying @var{function} on them
+before being sorted.  @var{function} is a function of one argument.
+
+@example
+(seq-sort-by #'seq-length #'> ["a" "ab" "abc"])
+@result{} ["abc" "ab" "a"]
+@end example
+@end defun
+
+
 @defun seq-contains sequence elt &optional function
   This function returns the first element in @var{sequence} that is equal to
 @var{elt}.  If the optional argument @var{function} is non-@code{nil},
index 8b7b594f5e181cfc8dff240ced0428e6e7d66e62..89fad4374273cc15848062423f9e7e054441fee5 100644 (file)
@@ -4,7 +4,7 @@
 
 ;; Author: Nicolas Petton <nicolas@petton.fr>
 ;; Keywords: sequences
-;; Version: 2.3
+;; Version: 2.14
 ;; Package: seq
 
 ;; Maintainer: emacs-devel@gnu.org
@@ -218,6 +218,16 @@ The result is a sequence of the same type as SEQUENCE."
 (cl-defmethod seq-sort (pred (list list))
   (sort (seq-copy list) pred))
 
+(defun seq-sort-by (function pred sequence)
+  "Sort SEQUENCE using PRED as a comparison function.
+Elements of SEQUENCE are transformed by FUNCTION before being
+sorted.  FUNCTION must be a function of one argument."
+  (seq-sort (lambda (a b)
+              (funcall pred
+                       (funcall function a)
+                       (funcall function b)))
+            sequence))
+
 (cl-defgeneric seq-reverse (sequence)
   "Return a sequence with elements of SEQUENCE in reverse order."
   (let ((result '()))
index c9219b51d00d96e37c2f81aa0416442c2b4256ec..50543de8ada93817a93d69a0c36ad190cb36b4ec 100644 (file)
@@ -347,5 +347,10 @@ Evaluate BODY for each created sequence.
     (should (= (seq-position seq 'a #'eq) 0))
     (should (null (seq-position seq (make-symbol "a") #'eq)))))
 
+(ert-deftest test-seq-sort-by ()
+  (let ((seq ["x" "xx" "xxx"]))
+    (should (equal (seq-sort-by #'seq-length #'> seq)
+                   ["xxx" "xx" "x"]))))
+
 (provide 'seq-tests)
 ;;; seq-tests.el ends here