]> code.delx.au - gnu-emacs/commitdiff
New function seq-map-indexed
authorNicolas Petton <nicolas@petton.fr>
Sun, 14 Feb 2016 09:25:10 +0000 (10:25 +0100)
committerNicolas Petton <nicolas@petton.fr>
Sun, 14 Feb 2016 09:25:10 +0000 (10:25 +0100)
* lisp/emacs-lisp/seq.el (seq-map-indexed): New function.
* test/lisp/emacs-lisp/seq-tests.el: Add tests for seq-map-indexed.

lisp/emacs-lisp/seq.el
test/lisp/emacs-lisp/seq-tests.el

index 300fe5cd1fd6c35f781879c76b6e9b2d9b4d7acb..8b7b594f5e181cfc8dff240ced0428e6e7d66e62 100644 (file)
@@ -144,6 +144,18 @@ if positive or too small if negative)."
             sequence)
     (nreverse result)))
 
+(defun seq-map-indexed (function sequence)
+  "Return the result of applying FUNCTION to each element of SEQUENCE.
+Unlike `seq-map', FUNCTION takes two arguments: the element of
+the sequence, and its index within the sequence."
+  (let ((index 0))
+    (seq-map (lambda (elt)
+               (prog1
+                   (funcall function elt index)
+                 (setq index (1+ index))))
+             sequence)))
+
+
 ;; faster implementation for sequences (sequencep)
 (cl-defmethod seq-map (function (sequence sequence))
   (mapcar function sequence))
index a8ca48b1328268a568277fc11d0e06152eca0296..c9219b51d00d96e37c2f81aa0416442c2b4256ec 100644 (file)
@@ -97,6 +97,16 @@ Evaluate BODY for each created sequence.
   (with-test-sequences (seq '())
     (should (seq-empty-p (seq-take-while #'test-sequences-oddp seq)))))
 
+(ert-deftest test-seq-map-indexed ()
+  (should (equal (seq-map-indexed (lambda (elt i)
+                                    (list elt i))
+                                  nil)
+                 nil))
+  (should (equal (seq-map-indexed (lambda (elt i)
+                                    (list elt i))
+                                  '(a b c d))
+                 '((a 0) (b 1) (c 2) (d 3)))))
+
 (ert-deftest test-seq-filter ()
   (with-test-sequences (seq '(6 7 8 9 10))
     (should (equal (seq-filter #'test-sequences-evenp seq) '(6 8 10)))