]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/seq.el
* lisp/emacs-lisp/seq.el: Load cl-lib, not cl-extra.
[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.3
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 (cl-defgeneric seqp (sequence)
121 "Return non-nil if SEQUENCE is a sequence, nil otherwise."
122 (sequencep sequence))
123
124 (cl-defgeneric seq-copy (sequence)
125 "Return a shallow copy of SEQUENCE."
126 (copy-sequence sequence))
127
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.
131
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))
137
138 \f
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)))
146
147 ;; faster implementation for sequences (sequencep)
148 (cl-defmethod seq-map (function (sequence sequence))
149 (mapcar function sequence))
150
151 (cl-defgeneric seq-mapn (function sequence &rest sequences)
152 "Like `seq-map' but FUNCTION is mapped over all SEQUENCES.
153 The arity of FUNCTION must match the number of SEQUENCES, and the
154 mapping stops on the shortest sequence.
155 Return a list of the results.
156
157 \(fn FUNCTION SEQUENCES...)"
158 (let ((result nil)
159 (sequences (seq-map (lambda (s) (seq-into s 'list))
160 (cons sequence sequences))))
161 (while (not (memq nil sequences))
162 (push (apply function (seq-map #'car sequences)) result)
163 (setq sequences (seq-map #'cdr sequences)))
164 (nreverse result)))
165
166 (cl-defgeneric seq-drop (sequence n)
167 "Remove the first N elements of SEQUENCE and return the result.
168 The result is a sequence of the same type as SEQUENCE.
169
170 If N is a negative integer or zero, SEQUENCE is returned."
171 (if (<= n 0)
172 sequence
173 (let ((length (seq-length sequence)))
174 (seq-subseq sequence (min n length) length))))
175
176 (cl-defgeneric seq-take (sequence n)
177 "Take the first N elements of SEQUENCE and return the result.
178 The result is a sequence of the same type as SEQUENCE.
179
180 If N is a negative integer or zero, an empty sequence is
181 returned."
182 (seq-subseq sequence 0 (min (max n 0) (seq-length sequence))))
183
184 (cl-defgeneric seq-drop-while (pred sequence)
185 "Remove the successive elements of SEQUENCE for which PRED returns non-nil.
186 PRED is a function of one argument. The result is a sequence of
187 the same type as SEQUENCE."
188 (seq-drop sequence (seq--count-successive pred sequence)))
189
190 (cl-defgeneric seq-take-while (pred sequence)
191 "Take the successive elements of SEQUENCE for which PRED returns non-nil.
192 PRED is a function of one argument. The result is a sequence of
193 the same type as SEQUENCE."
194 (seq-take sequence (seq--count-successive pred sequence)))
195
196 (cl-defgeneric seq-empty-p (sequence)
197 "Return non-nil if the SEQUENCE is empty, nil otherwise."
198 (= 0 (seq-length sequence)))
199
200 (cl-defgeneric seq-sort (pred sequence)
201 "Sort SEQUENCE using PRED as comparison function.
202 The result is a sequence of the same type as SEQUENCE."
203 (let ((result (seq-sort pred (append sequence nil))))
204 (seq-into result (type-of sequence))))
205
206 (cl-defmethod seq-sort (pred (list list))
207 (sort (seq-copy list) pred))
208
209 (cl-defgeneric seq-reverse (sequence)
210 "Return a sequence with elements of SEQUENCE in reverse order."
211 (let ((result '()))
212 (seq-map (lambda (elt)
213 (push elt result))
214 sequence)
215 (seq-into result (type-of sequence))))
216
217 ;; faster implementation for sequences (sequencep)
218 (cl-defmethod seq-reverse ((sequence sequence))
219 (reverse sequence))
220
221 (cl-defgeneric seq-concatenate (type &rest sequences)
222 "Concatenate SEQUENCES into a single sequence of type TYPE.
223 TYPE must be one of following symbols: vector, string or list.
224
225 \n(fn TYPE SEQUENCE...)"
226 (apply #'cl-concatenate type (seq-map #'seq-into-sequence sequences)))
227
228 (cl-defgeneric seq-into-sequence (sequence)
229 "Convert SEQUENCE into a sequence.
230
231 The default implementation is to signal an error if SEQUENCE is not a
232 sequence, specific functions should be implemented for new types
233 of sequence."
234 (unless (sequencep sequence)
235 (error "Cannot convert %S into a sequence" sequence))
236 sequence)
237
238 (cl-defgeneric seq-into (sequence type)
239 "Concatenate the elements of SEQUENCE into a sequence of type TYPE.
240 TYPE can be one of the following symbols: vector, string or
241 list."
242 (pcase type
243 (`vector (vconcat sequence))
244 (`string (concat sequence))
245 (`list (append sequence nil))
246 (_ (error "Not a sequence type name: %S" type))))
247
248 (cl-defgeneric seq-filter (pred sequence)
249 "Return a list of all the elements for which (PRED element) is non-nil in SEQUENCE."
250 (let ((exclude (make-symbol "exclude")))
251 (delq exclude (seq-map (lambda (elt)
252 (if (funcall pred elt)
253 elt
254 exclude))
255 sequence))))
256
257 (cl-defgeneric seq-remove (pred sequence)
258 "Return a list of all the elements for which (PRED element) is nil in SEQUENCE."
259 (seq-filter (lambda (elt) (not (funcall pred elt)))
260 sequence))
261
262 (cl-defgeneric seq-reduce (function sequence initial-value)
263 "Reduce the function FUNCTION across SEQUENCE, starting with INITIAL-VALUE.
264
265 Return the result of calling FUNCTION with INITIAL-VALUE and the
266 first element of SEQUENCE, then calling FUNCTION with that result and
267 the second element of SEQUENCE, then with that result and the third
268 element of SEQUENCE, etc.
269
270 If SEQUENCE is empty, return INITIAL-VALUE and FUNCTION is not called."
271 (if (seq-empty-p sequence)
272 initial-value
273 (let ((acc initial-value))
274 (seq-doseq (elt sequence)
275 (setq acc (funcall function acc elt)))
276 acc)))
277
278 (cl-defgeneric seq-every-p (pred sequence)
279 "Return non-nil if (PRED element) is non-nil for all elements of SEQUENCE."
280 (catch 'seq--break
281 (seq-doseq (elt sequence)
282 (or (funcall pred elt)
283 (throw 'seq--break nil)))
284 t))
285
286 (cl-defgeneric seq-some (pred sequence)
287 "Return the first value for which if (PRED element) is non-nil for in SEQUENCE."
288 (catch 'seq--break
289 (seq-doseq (elt sequence)
290 (let ((result (funcall pred elt)))
291 (when result
292 (throw 'seq--break result))))
293 nil))
294
295 (cl-defgeneric seq-find (pred sequence &optional default)
296 "Return the first element for which (PRED element) is non-nil in SEQUENCE.
297 If no element is found, return DEFAULT.
298
299 Note that `seq-find' has an ambiguity if the found element is
300 identical to DEFAULT, as it cannot be known if an element was
301 found or not."
302 (catch 'seq--break
303 (seq-doseq (elt sequence)
304 (when (funcall pred elt)
305 (throw 'seq--break elt)))
306 default))
307
308 (cl-defgeneric seq-count (pred sequence)
309 "Return the number of elements for which (PRED element) is non-nil in SEQUENCE."
310 (let ((count 0))
311 (seq-doseq (elt sequence)
312 (when (funcall pred elt)
313 (setq count (+ 1 count))))
314 count))
315
316 (cl-defgeneric seq-contains (sequence elt &optional testfn)
317 "Return the first element in SEQUENCE that is equal to ELT.
318 Equality is defined by TESTFN if non-nil or by `equal' if nil."
319 (seq-some (lambda (e)
320 (funcall (or testfn #'equal) elt e))
321 sequence))
322
323 (cl-defgeneric seq-position (sequence elt &optional testfn)
324 "Return the index of the first element in SEQUENCE that is equal to ELT.
325 Equality is defined by TESTFN if non-nil or by `equal' if nil."
326 (let ((index 0))
327 (catch 'seq--break
328 (seq-doseq (e sequence)
329 (when (funcall (or testfn #'equal) e elt)
330 (throw 'seq--break index))
331 (setq index (1+ index)))
332 nil)))
333
334 (cl-defgeneric seq-uniq (sequence &optional testfn)
335 "Return a list of the elements of SEQUENCE with duplicates removed.
336 TESTFN is used to compare elements, or `equal' if TESTFN is nil."
337 (let ((result '()))
338 (seq-doseq (elt sequence)
339 (unless (seq-contains result elt testfn)
340 (setq result (cons elt result))))
341 (nreverse result)))
342
343 (cl-defgeneric seq-mapcat (function sequence &optional type)
344 "Concatenate the result of applying FUNCTION to each element of SEQUENCE.
345 The result is a sequence of type TYPE, or a list if TYPE is nil."
346 (apply #'seq-concatenate (or type 'list)
347 (seq-map function sequence)))
348
349 (cl-defgeneric seq-partition (sequence n)
350 "Return a list of the elements of SEQUENCE grouped into sub-sequences of length N.
351 The last sequence may contain less than N elements. If N is a
352 negative integer or 0, nil is returned."
353 (unless (< n 1)
354 (let ((result '()))
355 (while (not (seq-empty-p sequence))
356 (push (seq-take sequence n) result)
357 (setq sequence (seq-drop sequence n)))
358 (nreverse result))))
359
360 (cl-defgeneric seq-intersection (sequence1 sequence2 &optional testfn)
361 "Return a list of the elements that appear in both SEQUENCE1 and SEQUENCE2.
362 Equality is defined by TESTFN if non-nil or by `equal' if nil."
363 (seq-reduce (lambda (acc elt)
364 (if (seq-contains sequence2 elt testfn)
365 (cons elt acc)
366 acc))
367 (seq-reverse sequence1)
368 '()))
369
370 (cl-defgeneric seq-difference (sequence1 sequence2 &optional testfn)
371 "Return a list of the elements that appear in SEQUENCE1 but not in SEQUENCE2.
372 Equality is defined by TESTFN if non-nil or by `equal' if nil."
373 (seq-reduce (lambda (acc elt)
374 (if (not (seq-contains sequence2 elt testfn))
375 (cons elt acc)
376 acc))
377 (seq-reverse sequence1)
378 '()))
379
380 (cl-defgeneric seq-group-by (function sequence)
381 "Apply FUNCTION to each element of SEQUENCE.
382 Separate the elements of SEQUENCE into an alist using the results as
383 keys. Keys are compared using `equal'."
384 (seq-reduce
385 (lambda (acc elt)
386 (let* ((key (funcall function elt))
387 (cell (assoc key acc)))
388 (if cell
389 (setcdr cell (push elt (cdr cell)))
390 (push (list key elt) acc))
391 acc))
392 (seq-reverse sequence)
393 nil))
394
395 (cl-defgeneric seq-min (sequence)
396 "Return the smallest element of SEQUENCE.
397 SEQUENCE must be a sequence of numbers or markers."
398 (apply #'min (seq-into sequence 'list)))
399
400 (cl-defgeneric seq-max (sequence)
401 "Return the largest element of SEQUENCE.
402 SEQUENCE must be a sequence of numbers or markers."
403 (apply #'max (seq-into sequence 'list)))
404
405 (defun seq--count-successive (pred sequence)
406 "Return the number of successive elements for which (PRED element) is non-nil in SEQUENCE."
407 (let ((n 0)
408 (len (seq-length sequence)))
409 (while (and (< n len)
410 (funcall pred (seq-elt sequence n)))
411 (setq n (+ 1 n)))
412 n))
413
414 (defun seq--make-pcase-bindings (args)
415 "Return a list of bindings of the variables in ARGS to the elements of a sequence."
416 (let ((bindings '())
417 (index 0)
418 (rest-marker nil))
419 (seq-doseq (name args)
420 (unless rest-marker
421 (pcase name
422 (`&rest
423 (progn (push `(app (pcase--flip seq-drop ,index)
424 ,(seq--elt-safe args (1+ index)))
425 bindings)
426 (setq rest-marker t)))
427 (_
428 (push `(app (pcase--flip seq--elt-safe ,index) ,name) bindings))))
429 (setq index (1+ index)))
430 bindings))
431
432 (defun seq--make-pcase-patterns (args)
433 "Return a list of `(seq ...)' pcase patterns from the argument list ARGS."
434 (cons 'seq
435 (seq-map (lambda (elt)
436 (if (seqp elt)
437 (seq--make-pcase-patterns elt)
438 elt))
439 args)))
440
441 ;; TODO: make public?
442 (defun seq--elt-safe (sequence n)
443 "Return element of SEQUENCE at the index N.
444 If no element is found, return nil."
445 (ignore-errors (seq-elt sequence n)))
446 \f
447
448 ;;; Optimized implementations for lists
449
450 (cl-defmethod seq-drop ((list list) n)
451 "Optimized implementation of `seq-drop' for lists."
452 (while (and list (> n 0))
453 (setq list (cdr list)
454 n (1- n)))
455 list)
456
457 (cl-defmethod seq-take ((list list) n)
458 "Optimized implementation of `seq-take' for lists."
459 (let ((result '()))
460 (while (and list (> n 0))
461 (setq n (1- n))
462 (push (pop list) result))
463 (nreverse result)))
464
465 (cl-defmethod seq-drop-while (pred (list list))
466 "Optimized implementation of `seq-drop-while' for lists."
467 (while (and list (funcall pred (car list)))
468 (setq list (cdr list)))
469 list)
470
471 (cl-defmethod seq-empty-p ((list list))
472 "Optimized implementation of `seq-empty-p' for lists."
473 (null list))
474 \f
475
476 (defun seq--activate-font-lock-keywords ()
477 "Activate font-lock keywords for some symbols defined in seq."
478 (font-lock-add-keywords 'emacs-lisp-mode
479 '("\\<seq-doseq\\>" "\\<seq-let\\>")))
480
481 (unless (fboundp 'elisp--font-lock-flush-elisp-buffers)
482 ;; In Emacsā‰„25, (via elisp--font-lock-flush-elisp-buffers and a few others)
483 ;; we automatically highlight macros.
484 (add-hook 'emacs-lisp-mode-hook #'seq--activate-font-lock-keywords))
485
486 (provide 'seq)
487 ;;; seq.el ends here