Rename comment-depth (etc.) to literal-cache (etc.). Enable it by default
[emacs.git] / lisp / emacs-lisp / seq.el
blob8b7b594f5e181cfc8dff240ced0428e6e7d66e62
1 ;;; seq.el --- Sequence manipulation functions -*- lexical-binding: t -*-
3 ;; Copyright (C) 2014-2016 Free Software Foundation, Inc.
5 ;; Author: Nicolas Petton <nicolas@petton.fr>
6 ;; Keywords: sequences
7 ;; Version: 2.3
8 ;; Package: seq
10 ;; Maintainer: emacs-devel@gnu.org
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; Sequence-manipulation functions that complement basic functions
30 ;; provided by subr.el.
32 ;; All functions are prefixed with "seq-".
34 ;; All provided functions work on lists, strings and vectors.
36 ;; Functions taking a predicate or iterating over a sequence using a
37 ;; function as argument take the function as their first argument and
38 ;; the sequence as their second argument. All other functions take
39 ;; the sequence as their first argument.
41 ;; While seq.el version 1.8 is in GNU ELPA for convenience, seq.el
42 ;; version 2.0 requires Emacs>=25.1.
44 ;; seq.el can be extended to support new type of sequences. Here are
45 ;; the generic functions that must be implemented by new seq types:
46 ;; - `seq-elt'
47 ;; - `seq-length'
48 ;; - `seq-do'
49 ;; - `seqp'
50 ;; - `seq-subseq'
51 ;; - `seq-into-sequence'
52 ;; - `seq-copy'
53 ;; - `seq-into'
55 ;; All functions are tested in test/automated/seq-tests.el
57 ;;; Code:
59 (eval-when-compile (require 'cl-generic))
60 (require 'cl-extra) ;; for cl-subseq
62 (defmacro seq-doseq (spec &rest body)
63 "Loop over a sequence.
64 Evaluate BODY with VAR bound to each element of SEQUENCE, in turn.
66 Similar to `dolist' but can be applied to lists, strings, and vectors.
68 \(fn (VAR SEQUENCE) BODY...)"
69 (declare (indent 1) (debug ((symbolp form &optional form) body)))
70 `(seq-do (lambda (,(car spec))
71 ,@body)
72 ,(cadr spec)))
74 (pcase-defmacro seq (&rest patterns)
75 "Build a `pcase' pattern that matches elements of SEQUENCE.
77 The `pcase' pattern will match each element of PATTERNS against the
78 corresponding element of SEQUENCE.
80 Extra elements of the sequence are ignored if fewer PATTERNS are
81 given, and the match does not fail."
82 `(and (pred seqp)
83 ,@(seq--make-pcase-bindings patterns)))
85 (defmacro seq-let (args sequence &rest body)
86 "Bind the variables in ARGS to the elements of SEQUENCE, then evaluate BODY.
88 ARGS can also include the `&rest' marker followed by a variable
89 name to be bound to the rest of SEQUENCE."
90 (declare (indent 2) (debug t))
91 `(pcase-let ((,(seq--make-pcase-patterns args) ,sequence))
92 ,@body))
95 ;;; Basic seq functions that have to be implemented by new sequence types
96 (cl-defgeneric seq-elt (sequence n)
97 "Return Nth element of SEQUENCE."
98 (elt sequence n))
100 ;; Default gv setters for `seq-elt'.
101 ;; It can be a good idea for new sequence implementations to provide a
102 ;; "gv-setter" for `seq-elt'.
103 (cl-defmethod (setf seq-elt) (store (sequence array) n)
104 (aset sequence n store))
106 (cl-defmethod (setf seq-elt) (store (sequence cons) n)
107 (setcar (nthcdr n sequence) store))
109 (cl-defgeneric seq-length (sequence)
110 "Return the number of elements of SEQUENCE."
111 (length sequence))
113 (cl-defgeneric seq-do (function sequence)
114 "Apply FUNCTION to each element of SEQUENCE, presumably for side effects.
115 Return SEQUENCE."
116 (mapc function sequence))
118 (defalias 'seq-each #'seq-do)
120 (cl-defgeneric seqp (sequence)
121 "Return non-nil if SEQUENCE is a sequence, nil otherwise."
122 (sequencep sequence))
124 (cl-defgeneric seq-copy (sequence)
125 "Return a shallow copy of SEQUENCE."
126 (copy-sequence sequence))
128 (cl-defgeneric seq-subseq (sequence start &optional end)
129 "Return the sequence of elements of SEQUENCE from START to END.
130 END is inclusive.
132 If END is omitted, it defaults to the length of the sequence. If
133 START or END is negative, it counts from the end. Signal an
134 error if START or END are outside of the sequence (i.e too large
135 if positive or too small if negative)."
136 (cl-subseq sequence start end))
139 (cl-defgeneric seq-map (function sequence)
140 "Return the result of applying FUNCTION to each element of SEQUENCE."
141 (let (result)
142 (seq-do (lambda (elt)
143 (push (funcall function elt) result))
144 sequence)
145 (nreverse result)))
147 (defun seq-map-indexed (function sequence)
148 "Return the result of applying FUNCTION to each element of SEQUENCE.
149 Unlike `seq-map', FUNCTION takes two arguments: the element of
150 the sequence, and its index within the sequence."
151 (let ((index 0))
152 (seq-map (lambda (elt)
153 (prog1
154 (funcall function elt index)
155 (setq index (1+ index))))
156 sequence)))
159 ;; faster implementation for sequences (sequencep)
160 (cl-defmethod seq-map (function (sequence sequence))
161 (mapcar function sequence))
163 (cl-defgeneric seq-mapn (function sequence &rest sequences)
164 "Like `seq-map' but FUNCTION is mapped over all SEQUENCES.
165 The arity of FUNCTION must match the number of SEQUENCES, and the
166 mapping stops on the shortest sequence.
167 Return a list of the results.
169 \(fn FUNCTION SEQUENCES...)"
170 (let ((result nil)
171 (sequences (seq-map (lambda (s) (seq-into s 'list))
172 (cons sequence sequences))))
173 (while (not (memq nil sequences))
174 (push (apply function (seq-map #'car sequences)) result)
175 (setq sequences (seq-map #'cdr sequences)))
176 (nreverse result)))
178 (cl-defgeneric seq-drop (sequence n)
179 "Remove the first N elements of SEQUENCE and return the result.
180 The result is a sequence of the same type as SEQUENCE.
182 If N is a negative integer or zero, SEQUENCE is returned."
183 (if (<= n 0)
184 sequence
185 (let ((length (seq-length sequence)))
186 (seq-subseq sequence (min n length) length))))
188 (cl-defgeneric seq-take (sequence n)
189 "Take the first N elements of SEQUENCE and return the result.
190 The result is a sequence of the same type as SEQUENCE.
192 If N is a negative integer or zero, an empty sequence is
193 returned."
194 (seq-subseq sequence 0 (min (max n 0) (seq-length sequence))))
196 (cl-defgeneric seq-drop-while (pred sequence)
197 "Remove the successive elements of SEQUENCE for which PRED returns non-nil.
198 PRED is a function of one argument. The result is a sequence of
199 the same type as SEQUENCE."
200 (seq-drop sequence (seq--count-successive pred sequence)))
202 (cl-defgeneric seq-take-while (pred sequence)
203 "Take the successive elements of SEQUENCE for which PRED returns non-nil.
204 PRED is a function of one argument. The result is a sequence of
205 the same type as SEQUENCE."
206 (seq-take sequence (seq--count-successive pred sequence)))
208 (cl-defgeneric seq-empty-p (sequence)
209 "Return non-nil if the SEQUENCE is empty, nil otherwise."
210 (= 0 (seq-length sequence)))
212 (cl-defgeneric seq-sort (pred sequence)
213 "Sort SEQUENCE using PRED as comparison function.
214 The result is a sequence of the same type as SEQUENCE."
215 (let ((result (seq-sort pred (append sequence nil))))
216 (seq-into result (type-of sequence))))
218 (cl-defmethod seq-sort (pred (list list))
219 (sort (seq-copy list) pred))
221 (cl-defgeneric seq-reverse (sequence)
222 "Return a sequence with elements of SEQUENCE in reverse order."
223 (let ((result '()))
224 (seq-map (lambda (elt)
225 (push elt result))
226 sequence)
227 (seq-into result (type-of sequence))))
229 ;; faster implementation for sequences (sequencep)
230 (cl-defmethod seq-reverse ((sequence sequence))
231 (reverse sequence))
233 (cl-defgeneric seq-concatenate (type &rest sequences)
234 "Concatenate SEQUENCES into a single sequence of type TYPE.
235 TYPE must be one of following symbols: vector, string or list.
237 \n(fn TYPE SEQUENCE...)"
238 (apply #'cl-concatenate type (seq-map #'seq-into-sequence sequences)))
240 (cl-defgeneric seq-into-sequence (sequence)
241 "Convert SEQUENCE into a sequence.
243 The default implementation is to signal an error if SEQUENCE is not a
244 sequence, specific functions should be implemented for new types
245 of sequence."
246 (unless (sequencep sequence)
247 (error "Cannot convert %S into a sequence" sequence))
248 sequence)
250 (cl-defgeneric seq-into (sequence type)
251 "Concatenate the elements of SEQUENCE into a sequence of type TYPE.
252 TYPE can be one of the following symbols: vector, string or
253 list."
254 (pcase type
255 (`vector (vconcat sequence))
256 (`string (concat sequence))
257 (`list (append sequence nil))
258 (_ (error "Not a sequence type name: %S" type))))
260 (cl-defgeneric seq-filter (pred sequence)
261 "Return a list of all the elements for which (PRED element) is non-nil in SEQUENCE."
262 (let ((exclude (make-symbol "exclude")))
263 (delq exclude (seq-map (lambda (elt)
264 (if (funcall pred elt)
266 exclude))
267 sequence))))
269 (cl-defgeneric seq-remove (pred sequence)
270 "Return a list of all the elements for which (PRED element) is nil in SEQUENCE."
271 (seq-filter (lambda (elt) (not (funcall pred elt)))
272 sequence))
274 (cl-defgeneric seq-reduce (function sequence initial-value)
275 "Reduce the function FUNCTION across SEQUENCE, starting with INITIAL-VALUE.
277 Return the result of calling FUNCTION with INITIAL-VALUE and the
278 first element of SEQUENCE, then calling FUNCTION with that result and
279 the second element of SEQUENCE, then with that result and the third
280 element of SEQUENCE, etc.
282 If SEQUENCE is empty, return INITIAL-VALUE and FUNCTION is not called."
283 (if (seq-empty-p sequence)
284 initial-value
285 (let ((acc initial-value))
286 (seq-doseq (elt sequence)
287 (setq acc (funcall function acc elt)))
288 acc)))
290 (cl-defgeneric seq-every-p (pred sequence)
291 "Return non-nil if (PRED element) is non-nil for all elements of SEQUENCE."
292 (catch 'seq--break
293 (seq-doseq (elt sequence)
294 (or (funcall pred elt)
295 (throw 'seq--break nil)))
298 (cl-defgeneric seq-some (pred sequence)
299 "Return the first value for which if (PRED element) is non-nil for in SEQUENCE."
300 (catch 'seq--break
301 (seq-doseq (elt sequence)
302 (let ((result (funcall pred elt)))
303 (when result
304 (throw 'seq--break result))))
305 nil))
307 (cl-defgeneric seq-find (pred sequence &optional default)
308 "Return the first element for which (PRED element) is non-nil in SEQUENCE.
309 If no element is found, return DEFAULT.
311 Note that `seq-find' has an ambiguity if the found element is
312 identical to DEFAULT, as it cannot be known if an element was
313 found or not."
314 (catch 'seq--break
315 (seq-doseq (elt sequence)
316 (when (funcall pred elt)
317 (throw 'seq--break elt)))
318 default))
320 (cl-defgeneric seq-count (pred sequence)
321 "Return the number of elements for which (PRED element) is non-nil in SEQUENCE."
322 (let ((count 0))
323 (seq-doseq (elt sequence)
324 (when (funcall pred elt)
325 (setq count (+ 1 count))))
326 count))
328 (cl-defgeneric seq-contains (sequence elt &optional testfn)
329 "Return the first element in SEQUENCE that is equal to ELT.
330 Equality is defined by TESTFN if non-nil or by `equal' if nil."
331 (seq-some (lambda (e)
332 (funcall (or testfn #'equal) elt e))
333 sequence))
335 (cl-defgeneric seq-position (sequence elt &optional testfn)
336 "Return the index of the first element in SEQUENCE that is equal to ELT.
337 Equality is defined by TESTFN if non-nil or by `equal' if nil."
338 (let ((index 0))
339 (catch 'seq--break
340 (seq-doseq (e sequence)
341 (when (funcall (or testfn #'equal) e elt)
342 (throw 'seq--break index))
343 (setq index (1+ index)))
344 nil)))
346 (cl-defgeneric seq-uniq (sequence &optional testfn)
347 "Return a list of the elements of SEQUENCE with duplicates removed.
348 TESTFN is used to compare elements, or `equal' if TESTFN is nil."
349 (let ((result '()))
350 (seq-doseq (elt sequence)
351 (unless (seq-contains result elt testfn)
352 (setq result (cons elt result))))
353 (nreverse result)))
355 (cl-defgeneric seq-mapcat (function sequence &optional type)
356 "Concatenate the result of applying FUNCTION to each element of SEQUENCE.
357 The result is a sequence of type TYPE, or a list if TYPE is nil."
358 (apply #'seq-concatenate (or type 'list)
359 (seq-map function sequence)))
361 (cl-defgeneric seq-partition (sequence n)
362 "Return a list of the elements of SEQUENCE grouped into sub-sequences of length N.
363 The last sequence may contain less than N elements. If N is a
364 negative integer or 0, nil is returned."
365 (unless (< n 1)
366 (let ((result '()))
367 (while (not (seq-empty-p sequence))
368 (push (seq-take sequence n) result)
369 (setq sequence (seq-drop sequence n)))
370 (nreverse result))))
372 (cl-defgeneric seq-intersection (sequence1 sequence2 &optional testfn)
373 "Return a list of the elements that appear in both SEQUENCE1 and SEQUENCE2.
374 Equality is defined by TESTFN if non-nil or by `equal' if nil."
375 (seq-reduce (lambda (acc elt)
376 (if (seq-contains sequence2 elt testfn)
377 (cons elt acc)
378 acc))
379 (seq-reverse sequence1)
380 '()))
382 (cl-defgeneric seq-difference (sequence1 sequence2 &optional testfn)
383 "Return a list of the elements that appear in SEQUENCE1 but not in SEQUENCE2.
384 Equality is defined by TESTFN if non-nil or by `equal' if nil."
385 (seq-reduce (lambda (acc elt)
386 (if (not (seq-contains sequence2 elt testfn))
387 (cons elt acc)
388 acc))
389 (seq-reverse sequence1)
390 '()))
392 (cl-defgeneric seq-group-by (function sequence)
393 "Apply FUNCTION to each element of SEQUENCE.
394 Separate the elements of SEQUENCE into an alist using the results as
395 keys. Keys are compared using `equal'."
396 (seq-reduce
397 (lambda (acc elt)
398 (let* ((key (funcall function elt))
399 (cell (assoc key acc)))
400 (if cell
401 (setcdr cell (push elt (cdr cell)))
402 (push (list key elt) acc))
403 acc))
404 (seq-reverse sequence)
405 nil))
407 (cl-defgeneric seq-min (sequence)
408 "Return the smallest element of SEQUENCE.
409 SEQUENCE must be a sequence of numbers or markers."
410 (apply #'min (seq-into sequence 'list)))
412 (cl-defgeneric seq-max (sequence)
413 "Return the largest element of SEQUENCE.
414 SEQUENCE must be a sequence of numbers or markers."
415 (apply #'max (seq-into sequence 'list)))
417 (defun seq--count-successive (pred sequence)
418 "Return the number of successive elements for which (PRED element) is non-nil in SEQUENCE."
419 (let ((n 0)
420 (len (seq-length sequence)))
421 (while (and (< n len)
422 (funcall pred (seq-elt sequence n)))
423 (setq n (+ 1 n)))
426 (defun seq--make-pcase-bindings (args)
427 "Return a list of bindings of the variables in ARGS to the elements of a sequence."
428 (let ((bindings '())
429 (index 0)
430 (rest-marker nil))
431 (seq-doseq (name args)
432 (unless rest-marker
433 (pcase name
434 (`&rest
435 (progn (push `(app (pcase--flip seq-drop ,index)
436 ,(seq--elt-safe args (1+ index)))
437 bindings)
438 (setq rest-marker t)))
440 (push `(app (pcase--flip seq--elt-safe ,index) ,name) bindings))))
441 (setq index (1+ index)))
442 bindings))
444 (defun seq--make-pcase-patterns (args)
445 "Return a list of `(seq ...)' pcase patterns from the argument list ARGS."
446 (cons 'seq
447 (seq-map (lambda (elt)
448 (if (seqp elt)
449 (seq--make-pcase-patterns elt)
450 elt))
451 args)))
453 ;; TODO: make public?
454 (defun seq--elt-safe (sequence n)
455 "Return element of SEQUENCE at the index N.
456 If no element is found, return nil."
457 (ignore-errors (seq-elt sequence n)))
460 ;;; Optimized implementations for lists
462 (cl-defmethod seq-drop ((list list) n)
463 "Optimized implementation of `seq-drop' for lists."
464 (while (and list (> n 0))
465 (setq list (cdr list)
466 n (1- n)))
467 list)
469 (cl-defmethod seq-take ((list list) n)
470 "Optimized implementation of `seq-take' for lists."
471 (let ((result '()))
472 (while (and list (> n 0))
473 (setq n (1- n))
474 (push (pop list) result))
475 (nreverse result)))
477 (cl-defmethod seq-drop-while (pred (list list))
478 "Optimized implementation of `seq-drop-while' for lists."
479 (while (and list (funcall pred (car list)))
480 (setq list (cdr list)))
481 list)
483 (cl-defmethod seq-empty-p ((list list))
484 "Optimized implementation of `seq-empty-p' for lists."
485 (null list))
488 (defun seq--activate-font-lock-keywords ()
489 "Activate font-lock keywords for some symbols defined in seq."
490 (font-lock-add-keywords 'emacs-lisp-mode
491 '("\\<seq-doseq\\>" "\\<seq-let\\>")))
493 (unless (fboundp 'elisp--font-lock-flush-elisp-buffers)
494 ;; In Emacsā‰„25, (via elisp--font-lock-flush-elisp-buffers and a few others)
495 ;; we automatically highlight macros.
496 (add-hook 'emacs-lisp-mode-hook #'seq--activate-font-lock-keywords))
498 (provide 'seq)
499 ;;; seq.el ends here