]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/seq.el
; Fix breakage from previous commit
[gnu-emacs] / lisp / emacs-lisp / seq.el
1 ;;; seq.el --- Sequence manipulation functions -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2014-2016 Free Software Foundation, Inc.
4
5 ;; Author: Nicolas Petton <nicolas@petton.fr>
6 ;; Keywords: sequences
7 ;; Version: 2.18
8 ;; Package: seq
9
10 ;; Maintainer: emacs-devel@gnu.org
11
12 ;; This file is part of GNU Emacs.
13
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.
18
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.
23
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/>.
26
27 ;;; Commentary:
28
29 ;; Sequence-manipulation functions that complement basic functions
30 ;; provided by subr.el.
31 ;;
32 ;; All functions are prefixed with "seq-".
33 ;;
34 ;; All provided functions work on lists, strings and vectors.
35 ;;
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.
40 ;;
41 ;; While seq.el version 1.8 is in GNU ELPA for convenience, seq.el
42 ;; version 2.0 requires Emacs>=25.1.
43 ;;
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'
54 ;;
55 ;; All functions are tested in test/automated/seq-tests.el
56
57 ;;; Code:
58
59 (eval-when-compile (require 'cl-generic))
60 (require 'cl-lib) ;; for cl-subseq
61
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.
65
66 Similar to `dolist' but can be applied to lists, strings, and vectors.
67
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)))
73
74 (pcase-defmacro seq (&rest patterns)
75 "Build a `pcase' pattern that matches elements of SEQUENCE.
76
77 The `pcase' pattern will match each element of PATTERNS against the
78 corresponding element of SEQUENCE.
79
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)))
84
85 (defmacro seq-let (args sequence &rest body)
86 "Bind the variables in ARGS to the elements of SEQUENCE, then evaluate BODY.
87
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))
93 \f
94
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))
99
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))
105
106 (cl-defmethod (setf seq-elt) (store (sequence cons) n)
107 (setcar (nthcdr n sequence) store))
108
109 (cl-defgeneric seq-length (sequence)
110 "Return the number of elements of SEQUENCE."
111 (length sequence))
112
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))
117
118 (defalias 'seq-each #'seq-do)
119
120 (defun seq-do-indexed (function sequence)
121 "Apply FUNCTION to each element of SEQUENCE and return nil.
122 Unlike `seq-map', FUNCTION takes two arguments: the element of
123 the sequence, and its index within the sequence."
124 (let ((index 0))
125 (seq-do (lambda (elt)
126 (funcall function elt index)
127 (setq index (1+ index)))
128 sequence)))
129
130 (cl-defgeneric seqp (sequence)
131 "Return non-nil if SEQUENCE is a sequence, nil otherwise."
132 (sequencep sequence))
133
134 (cl-defgeneric seq-copy (sequence)
135 "Return a shallow copy of SEQUENCE."
136 (copy-sequence sequence))
137
138 (cl-defgeneric seq-subseq (sequence start &optional end)
139 "Return the sequence of elements of SEQUENCE from START to END.
140 END is inclusive.
141
142 If END is omitted, it defaults to the length of the sequence. If
143 START or END is negative, it counts from the end. Signal an
144 error if START or END are outside of the sequence (i.e too large
145 if positive or too small if negative)."
146 (cl-subseq sequence start end))
147
148 \f
149 (cl-defgeneric seq-map (function sequence)
150 "Return the result of applying FUNCTION to each element of SEQUENCE."
151 (let (result)
152 (seq-do (lambda (elt)
153 (push (funcall function elt) result))
154 sequence)
155 (nreverse result)))
156
157 (defun seq-map-indexed (function sequence)
158 "Return the result of applying FUNCTION to each element of SEQUENCE.
159 Unlike `seq-map', FUNCTION takes two arguments: the element of
160 the sequence, and its index within the sequence."
161 (let ((index 0))
162 (seq-map (lambda (elt)
163 (prog1
164 (funcall function elt index)
165 (setq index (1+ index))))
166 sequence)))
167
168
169 ;; faster implementation for sequences (sequencep)
170 (cl-defmethod seq-map (function (sequence sequence))
171 (mapcar function sequence))
172
173 (cl-defgeneric seq-mapn (function sequence &rest sequences)
174 "Like `seq-map' but FUNCTION is mapped over all SEQUENCES.
175 The arity of FUNCTION must match the number of SEQUENCES, and the
176 mapping stops on the shortest sequence.
177 Return a list of the results.
178
179 \(fn FUNCTION SEQUENCES...)"
180 (let ((result nil)
181 (sequences (seq-map (lambda (s) (seq-into s 'list))
182 (cons sequence sequences))))
183 (while (not (memq nil sequences))
184 (push (apply function (seq-map #'car sequences)) result)
185 (setq sequences (seq-map #'cdr sequences)))
186 (nreverse result)))
187
188 (cl-defgeneric seq-drop (sequence n)
189 "Remove the first N elements of SEQUENCE and return the result.
190 The result is a sequence of the same type as SEQUENCE.
191
192 If N is a negative integer or zero, SEQUENCE is returned."
193 (if (<= n 0)
194 sequence
195 (let ((length (seq-length sequence)))
196 (seq-subseq sequence (min n length) length))))
197
198 (cl-defgeneric seq-take (sequence n)
199 "Take the first N elements of SEQUENCE and return the result.
200 The result is a sequence of the same type as SEQUENCE.
201
202 If N is a negative integer or zero, an empty sequence is
203 returned."
204 (seq-subseq sequence 0 (min (max n 0) (seq-length sequence))))
205
206 (cl-defgeneric seq-drop-while (pred sequence)
207 "Remove the successive elements of SEQUENCE for which PRED returns non-nil.
208 PRED is a function of one argument. The result is a sequence of
209 the same type as SEQUENCE."
210 (seq-drop sequence (seq--count-successive pred sequence)))
211
212 (cl-defgeneric seq-take-while (pred sequence)
213 "Take the successive elements of SEQUENCE for which PRED returns non-nil.
214 PRED is a function of one argument. The result is a sequence of
215 the same type as SEQUENCE."
216 (seq-take sequence (seq--count-successive pred sequence)))
217
218 (cl-defgeneric seq-empty-p (sequence)
219 "Return non-nil if the SEQUENCE is empty, nil otherwise."
220 (= 0 (seq-length sequence)))
221
222 (cl-defgeneric seq-sort (pred sequence)
223 "Sort SEQUENCE using PRED as comparison function.
224 The result is a sequence of the same type as SEQUENCE."
225 (let ((result (seq-sort pred (append sequence nil))))
226 (seq-into result (type-of sequence))))
227
228 (cl-defmethod seq-sort (pred (list list))
229 (sort (seq-copy list) pred))
230
231 (defun seq-sort-by (function pred sequence)
232 "Sort SEQUENCE using PRED as a comparison function.
233 Elements of SEQUENCE are transformed by FUNCTION before being
234 sorted. FUNCTION must be a function of one argument."
235 (seq-sort (lambda (a b)
236 (funcall pred
237 (funcall function a)
238 (funcall function b)))
239 sequence))
240
241 (cl-defgeneric seq-reverse (sequence)
242 "Return a sequence with elements of SEQUENCE in reverse order."
243 (let ((result '()))
244 (seq-map (lambda (elt)
245 (push elt result))
246 sequence)
247 (seq-into result (type-of sequence))))
248
249 ;; faster implementation for sequences (sequencep)
250 (cl-defmethod seq-reverse ((sequence sequence))
251 (reverse sequence))
252
253 (cl-defgeneric seq-concatenate (type &rest sequences)
254 "Concatenate SEQUENCES into a single sequence of type TYPE.
255 TYPE must be one of following symbols: vector, string or list.
256
257 \n(fn TYPE SEQUENCE...)"
258 (apply #'cl-concatenate type (seq-map #'seq-into-sequence sequences)))
259
260 (cl-defgeneric seq-into-sequence (sequence)
261 "Convert SEQUENCE into a sequence.
262
263 The default implementation is to signal an error if SEQUENCE is not a
264 sequence, specific functions should be implemented for new types
265 of sequence."
266 (unless (sequencep sequence)
267 (error "Cannot convert %S into a sequence" sequence))
268 sequence)
269
270 (cl-defgeneric seq-into (sequence type)
271 "Concatenate the elements of SEQUENCE into a sequence of type TYPE.
272 TYPE can be one of the following symbols: vector, string or
273 list."
274 (pcase type
275 (`vector (vconcat sequence))
276 (`string (concat sequence))
277 (`list (append sequence nil))
278 (_ (error "Not a sequence type name: %S" type))))
279
280 (cl-defgeneric seq-filter (pred sequence)
281 "Return a list of all the elements for which (PRED element) is non-nil in SEQUENCE."
282 (let ((exclude (make-symbol "exclude")))
283 (delq exclude (seq-map (lambda (elt)
284 (if (funcall pred elt)
285 elt
286 exclude))
287 sequence))))
288
289 (cl-defgeneric seq-remove (pred sequence)
290 "Return a list of all the elements for which (PRED element) is nil in SEQUENCE."
291 (seq-filter (lambda (elt) (not (funcall pred elt)))
292 sequence))
293
294 (cl-defgeneric seq-reduce (function sequence initial-value)
295 "Reduce the function FUNCTION across SEQUENCE, starting with INITIAL-VALUE.
296
297 Return the result of calling FUNCTION with INITIAL-VALUE and the
298 first element of SEQUENCE, then calling FUNCTION with that result and
299 the second element of SEQUENCE, then with that result and the third
300 element of SEQUENCE, etc.
301
302 If SEQUENCE is empty, return INITIAL-VALUE and FUNCTION is not called."
303 (if (seq-empty-p sequence)
304 initial-value
305 (let ((acc initial-value))
306 (seq-doseq (elt sequence)
307 (setq acc (funcall function acc elt)))
308 acc)))
309
310 (cl-defgeneric seq-every-p (pred sequence)
311 "Return non-nil if (PRED element) is non-nil for all elements of SEQUENCE."
312 (catch 'seq--break
313 (seq-doseq (elt sequence)
314 (or (funcall pred elt)
315 (throw 'seq--break nil)))
316 t))
317
318 (cl-defgeneric seq-some (pred sequence)
319 "Return the first value for which if (PRED element) is non-nil for in SEQUENCE."
320 (catch 'seq--break
321 (seq-doseq (elt sequence)
322 (let ((result (funcall pred elt)))
323 (when result
324 (throw 'seq--break result))))
325 nil))
326
327 (cl-defgeneric seq-find (pred sequence &optional default)
328 "Return the first element for which (PRED element) is non-nil in SEQUENCE.
329 If no element is found, return DEFAULT.
330
331 Note that `seq-find' has an ambiguity if the found element is
332 identical to DEFAULT, as it cannot be known if an element was
333 found or not."
334 (catch 'seq--break
335 (seq-doseq (elt sequence)
336 (when (funcall pred elt)
337 (throw 'seq--break elt)))
338 default))
339
340 (cl-defgeneric seq-count (pred sequence)
341 "Return the number of elements for which (PRED element) is non-nil in SEQUENCE."
342 (let ((count 0))
343 (seq-doseq (elt sequence)
344 (when (funcall pred elt)
345 (setq count (+ 1 count))))
346 count))
347
348 (cl-defgeneric seq-contains (sequence elt &optional testfn)
349 "Return the first element in SEQUENCE that is equal to ELT.
350 Equality is defined by TESTFN if non-nil or by `equal' if nil."
351 (seq-some (lambda (e)
352 (when (funcall (or testfn #'equal) elt e)
353 e))
354 sequence))
355
356 (cl-defgeneric seq-position (sequence elt &optional testfn)
357 "Return the index of the first element in SEQUENCE that is equal to ELT.
358 Equality is defined by TESTFN if non-nil or by `equal' if nil."
359 (let ((index 0))
360 (catch 'seq--break
361 (seq-doseq (e sequence)
362 (when (funcall (or testfn #'equal) e elt)
363 (throw 'seq--break index))
364 (setq index (1+ index)))
365 nil)))
366
367 (cl-defgeneric seq-uniq (sequence &optional testfn)
368 "Return a list of the elements of SEQUENCE with duplicates removed.
369 TESTFN is used to compare elements, or `equal' if TESTFN is nil."
370 (let ((result '()))
371 (seq-doseq (elt sequence)
372 (unless (seq-contains result elt testfn)
373 (setq result (cons elt result))))
374 (nreverse result)))
375
376 (cl-defgeneric seq-mapcat (function sequence &optional type)
377 "Concatenate the result of applying FUNCTION to each element of SEQUENCE.
378 The result is a sequence of type TYPE, or a list if TYPE is nil."
379 (apply #'seq-concatenate (or type 'list)
380 (seq-map function sequence)))
381
382 (cl-defgeneric seq-partition (sequence n)
383 "Return a list of the elements of SEQUENCE grouped into sub-sequences of length N.
384 The last sequence may contain less than N elements. If N is a
385 negative integer or 0, nil is returned."
386 (unless (< n 1)
387 (let ((result '()))
388 (while (not (seq-empty-p sequence))
389 (push (seq-take sequence n) result)
390 (setq sequence (seq-drop sequence n)))
391 (nreverse result))))
392
393 (cl-defgeneric seq-intersection (sequence1 sequence2 &optional testfn)
394 "Return a list of the elements that appear in both SEQUENCE1 and SEQUENCE2.
395 Equality is defined by TESTFN if non-nil or by `equal' if nil."
396 (seq-reduce (lambda (acc elt)
397 (if (seq-contains sequence2 elt testfn)
398 (cons elt acc)
399 acc))
400 (seq-reverse sequence1)
401 '()))
402
403 (cl-defgeneric seq-difference (sequence1 sequence2 &optional testfn)
404 "Return a list of the elements that appear in SEQUENCE1 but not in SEQUENCE2.
405 Equality is defined by TESTFN if non-nil or by `equal' if nil."
406 (seq-reduce (lambda (acc elt)
407 (if (not (seq-contains sequence2 elt testfn))
408 (cons elt acc)
409 acc))
410 (seq-reverse sequence1)
411 '()))
412
413 (cl-defgeneric seq-group-by (function sequence)
414 "Apply FUNCTION to each element of SEQUENCE.
415 Separate the elements of SEQUENCE into an alist using the results as
416 keys. Keys are compared using `equal'."
417 (seq-reduce
418 (lambda (acc elt)
419 (let* ((key (funcall function elt))
420 (cell (assoc key acc)))
421 (if cell
422 (setcdr cell (push elt (cdr cell)))
423 (push (list key elt) acc))
424 acc))
425 (seq-reverse sequence)
426 nil))
427
428 (cl-defgeneric seq-min (sequence)
429 "Return the smallest element of SEQUENCE.
430 SEQUENCE must be a sequence of numbers or markers."
431 (apply #'min (seq-into sequence 'list)))
432
433 (cl-defgeneric seq-max (sequence)
434 "Return the largest element of SEQUENCE.
435 SEQUENCE must be a sequence of numbers or markers."
436 (apply #'max (seq-into sequence 'list)))
437
438 (defun seq--count-successive (pred sequence)
439 "Return the number of successive elements for which (PRED element) is non-nil in SEQUENCE."
440 (let ((n 0)
441 (len (seq-length sequence)))
442 (while (and (< n len)
443 (funcall pred (seq-elt sequence n)))
444 (setq n (+ 1 n)))
445 n))
446
447 (defun seq--make-pcase-bindings (args)
448 "Return a list of bindings of the variables in ARGS to the elements of a sequence."
449 (let ((bindings '())
450 (index 0)
451 (rest-marker nil))
452 (seq-doseq (name args)
453 (unless rest-marker
454 (pcase name
455 (`&rest
456 (progn (push `(app (pcase--flip seq-drop ,index)
457 ,(seq--elt-safe args (1+ index)))
458 bindings)
459 (setq rest-marker t)))
460 (_
461 (push `(app (pcase--flip seq--elt-safe ,index) ,name) bindings))))
462 (setq index (1+ index)))
463 bindings))
464
465 (defun seq--make-pcase-patterns (args)
466 "Return a list of `(seq ...)' pcase patterns from the argument list ARGS."
467 (cons 'seq
468 (seq-map (lambda (elt)
469 (if (seqp elt)
470 (seq--make-pcase-patterns elt)
471 elt))
472 args)))
473
474 ;; TODO: make public?
475 (defun seq--elt-safe (sequence n)
476 "Return element of SEQUENCE at the index N.
477 If no element is found, return nil."
478 (ignore-errors (seq-elt sequence n)))
479 \f
480
481 ;;; Optimized implementations for lists
482
483 (cl-defmethod seq-drop ((list list) n)
484 "Optimized implementation of `seq-drop' for lists."
485 (nthcdr n list))
486
487 (cl-defmethod seq-take ((list list) n)
488 "Optimized implementation of `seq-take' for lists."
489 (let ((result '()))
490 (while (and list (> n 0))
491 (setq n (1- n))
492 (push (pop list) result))
493 (nreverse result)))
494
495 (cl-defmethod seq-drop-while (pred (list list))
496 "Optimized implementation of `seq-drop-while' for lists."
497 (while (and list (funcall pred (car list)))
498 (setq list (cdr list)))
499 list)
500
501 (cl-defmethod seq-empty-p ((list list))
502 "Optimized implementation of `seq-empty-p' for lists."
503 (null list))
504 \f
505
506 (defun seq--activate-font-lock-keywords ()
507 "Activate font-lock keywords for some symbols defined in seq."
508 (font-lock-add-keywords 'emacs-lisp-mode
509 '("\\<seq-doseq\\>" "\\<seq-let\\>")))
510
511 (unless (fboundp 'elisp--font-lock-flush-elisp-buffers)
512 ;; In Emacsā‰„25, (via elisp--font-lock-flush-elisp-buffers and a few others)
513 ;; we automatically highlight macros.
514 (add-hook 'emacs-lisp-mode-hook #'seq--activate-font-lock-keywords))
515
516 (provide 'seq)
517 ;;; seq.el ends here