]> code.delx.au - gnu-emacs-elpa/blob - packages/seq/seq.el
* packages/seq: Don't define it as a :core package
[gnu-emacs-elpa] / packages / seq / seq.el
1 ;;; seq.el --- Sequence manipulation functions -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2014-2015 Free Software Foundation, Inc.
4
5 ;; Author: Nicolas Petton <nicolas@petton.fr>
6 ;; Keywords: sequences
7 ;; Version: 1.11
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 ;; All functions are tested in test/automated/seq-tests.el
42
43 ;;; Code:
44
45 (defmacro seq-doseq (spec &rest body)
46 "Loop over a sequence.
47 Similar to `dolist' but can be applied to lists, strings, and vectors.
48
49 Evaluate BODY with VAR bound to each element of SEQ, in turn.
50
51 \(fn (VAR SEQ) BODY...)"
52 (declare (indent 1) (debug ((symbolp form &optional form) body)))
53 (let ((length (make-symbol "length"))
54 (seq (make-symbol "seq"))
55 (index (make-symbol "index")))
56 `(let* ((,seq ,(cadr spec))
57 (,length (if (listp ,seq) nil (seq-length ,seq)))
58 (,index (if ,length 0 ,seq)))
59 (while (if ,length
60 (< ,index ,length)
61 (consp ,index))
62 (let ((,(car spec) (if ,length
63 (prog1 (seq-elt ,seq ,index)
64 (setq ,index (+ ,index 1)))
65 (pop ,index))))
66 ,@body)))))
67
68 (if (fboundp 'pcase-defmacro)
69 ;; Implementation of `seq-let' based on a `pcase'
70 ;; pattern. Requires Emacs>=25.1.
71 (progn
72 (pcase-defmacro seq (&rest args)
73 "pcase pattern matching sequence elements.
74 Matches if the object is a sequence (list, string or vector), and
75 binds each element of ARGS to the corresponding element of the
76 sequence."
77 `(and (pred seq-p)
78 ,@(seq--make-pcase-bindings args)))
79
80 (defmacro seq-let (args seq &rest body)
81 "Bind the variables in ARGS to the elements of SEQ then evaluate BODY.
82
83 ARGS can also include the `&rest' marker followed by a variable
84 name to be bound to the rest of SEQ."
85 (declare (indent 2) (debug t))
86 `(pcase-let ((,(seq--make-pcase-patterns args) ,seq))
87 ,@body)))
88
89 ;; Implementation of `seq-let' compatible with Emacs<25.1.
90 (defmacro seq-let (args seq &rest body)
91 "Bind the variables in ARGS to the elements of SEQ then evaluate BODY.
92
93 ARGS can also include the `&rest' marker followed by a variable
94 name to be bound to the rest of SEQ."
95 (declare (indent 2) (debug t))
96 (let ((seq-var (make-symbol "seq")))
97 `(let* ((,seq-var ,seq)
98 ,@(seq--make-bindings args seq-var))
99 ,@body))))
100
101 (defun seq-drop (seq n)
102 "Return a subsequence of SEQ without its first N elements.
103 The result is a sequence of the same type as SEQ.
104
105 If N is a negative integer or zero, SEQ is returned."
106 (if (<= n 0)
107 seq
108 (if (listp seq)
109 (seq--drop-list seq n)
110 (let ((length (seq-length seq)))
111 (seq-subseq seq (min n length) length)))))
112
113 (defun seq-take (seq n)
114 "Return a subsequence of SEQ with its first N elements.
115 The result is a sequence of the same type as SEQ.
116
117 If N is a negative integer or zero, an empty sequence is
118 returned."
119 (if (listp seq)
120 (seq--take-list seq n)
121 (seq-subseq seq 0 (min (max n 0) (seq-length seq)))))
122
123 (defun seq-drop-while (pred seq)
124 "Return a sequence from the first element for which (PRED element) is nil in SEQ.
125 The result is a sequence of the same type as SEQ."
126 (if (listp seq)
127 (seq--drop-while-list pred seq)
128 (seq-drop seq (seq--count-successive pred seq))))
129
130 (defun seq-take-while (pred seq)
131 "Return the successive elements for which (PRED element) is non-nil in SEQ.
132 The result is a sequence of the same type as SEQ."
133 (if (listp seq)
134 (seq--take-while-list pred seq)
135 (seq-take seq (seq--count-successive pred seq))))
136
137 (defun seq-filter (pred seq)
138 "Return a list of all the elements for which (PRED element) is non-nil in SEQ."
139 (let ((exclude (make-symbol "exclude")))
140 (delq exclude (seq-map (lambda (elt)
141 (if (funcall pred elt)
142 elt
143 exclude))
144 seq))))
145
146 (defun seq-remove (pred seq)
147 "Return a list of all the elements for which (PRED element) is nil in SEQ."
148 (seq-filter (lambda (elt) (not (funcall pred elt)))
149 seq))
150
151 (defun seq-reduce (function seq initial-value)
152 "Reduce the function FUNCTION across SEQ, starting with INITIAL-VALUE.
153
154 Return the result of calling FUNCTION with INITIAL-VALUE and the
155 first element of SEQ, then calling FUNCTION with that result and
156 the second element of SEQ, then with that result and the third
157 element of SEQ, etc.
158
159 If SEQ is empty, return INITIAL-VALUE and FUNCTION is not called."
160 (if (seq-empty-p seq)
161 initial-value
162 (let ((acc initial-value))
163 (seq-doseq (elt seq)
164 (setq acc (funcall function acc elt)))
165 acc)))
166
167 (defun seq-some (pred seq)
168 "Return the first value for which if (PRED element) is non-nil for in SEQ."
169 (catch 'seq--break
170 (seq-doseq (elt seq)
171 (let ((result (funcall pred elt)))
172 (when result
173 (throw 'seq--break result))))
174 nil))
175
176 (defun seq-find (pred seq &optional default)
177 "Return the first element for which (PRED element) is non-nil in SEQ.
178 If no element is found, return DEFAULT.
179
180 Note that `seq-find' has an ambiguity if the found element is
181 identical to DEFAULT, as it cannot be known if an element was
182 found or not."
183 (catch 'seq--break
184 (seq-doseq (elt seq)
185 (when (funcall pred elt)
186 (throw 'seq--break elt)))
187 default))
188
189 (defun seq-every-p (pred seq)
190 "Return non-nil if (PRED element) is non-nil for all elements of the sequence SEQ."
191 (catch 'seq--break
192 (seq-doseq (elt seq)
193 (or (funcall pred elt)
194 (throw 'seq--break nil)))
195 t))
196
197 (defun seq-count (pred seq)
198 "Return the number of elements for which (PRED element) is non-nil in SEQ."
199 (let ((count 0))
200 (seq-doseq (elt seq)
201 (when (funcall pred elt)
202 (setq count (+ 1 count))))
203 count))
204
205 (defun seq-empty-p (seq)
206 "Return non-nil if the sequence SEQ is empty, nil otherwise."
207 (if (listp seq)
208 (null seq)
209 (= 0 (seq-length seq))))
210
211 (defun seq-sort (pred seq)
212 "Return a sorted sequence comparing using PRED the elements of SEQ.
213 The result is a sequence of the same type as SEQ."
214 (if (listp seq)
215 (sort (seq-copy seq) pred)
216 (let ((result (seq-sort pred (append seq nil))))
217 (seq-into result (type-of seq)))))
218
219 (defun seq-contains (seq elt &optional testfn)
220 "Return the first element in SEQ that equals to ELT.
221 Equality is defined by TESTFN if non-nil or by `equal' if nil."
222 (seq-some (lambda (e)
223 (funcall (or testfn #'equal) elt e))
224 seq))
225
226 (defun seq-position (seq elt &optional testfn)
227 "Return the index of the first element in SEQ that is equal to ELT.
228 Equality is defined by TESTFN if non-nil or by `equal' if nil."
229 (let ((index 0))
230 (catch 'seq--break
231 (seq-doseq (e seq)
232 (when (funcall (or testfn #'equal) e elt)
233 (throw 'seq--break index))
234 (setq index (1+ index)))
235 nil)))
236
237 (defun seq-uniq (seq &optional testfn)
238 "Return a list of the elements of SEQ with duplicates removed.
239 TESTFN is used to compare elements, or `equal' if TESTFN is nil."
240 (let ((result '()))
241 (seq-doseq (elt seq)
242 (unless (seq-contains result elt testfn)
243 (setq result (cons elt result))))
244 (nreverse result)))
245
246 (defun seq-subseq (seq start &optional end)
247 "Return the subsequence of SEQ from START to END.
248 If END is omitted, it defaults to the length of the sequence.
249 If START or END is negative, it counts from the end."
250 (cond ((or (stringp seq) (vectorp seq)) (substring seq start end))
251 ((listp seq)
252 (let (len (errtext (format "Bad bounding indices: %s, %s" start end)))
253 (and end (< end 0) (setq end (+ end (setq len (seq-length seq)))))
254 (if (< start 0) (setq start (+ start (or len (setq len (seq-length seq))))))
255 (when (> start 0)
256 (setq seq (nthcdr (1- start) seq))
257 (or seq (error "%s" errtext))
258 (setq seq (cdr seq)))
259 (if end
260 (let ((res nil))
261 (while (and (>= (setq end (1- end)) start) seq)
262 (push (pop seq) res))
263 (or (= (1+ end) start) (error "%s" errtext))
264 (nreverse res))
265 (seq-copy seq))))
266 (t (error "Unsupported sequence: %s" seq))))
267
268 (defun seq-concatenate (type &rest seqs)
269 "Concatenate, into a sequence of type TYPE, the sequences SEQS.
270 TYPE must be one of following symbols: vector, string or list.
271
272 \n(fn TYPE SEQUENCE...)"
273 (pcase type
274 (`vector (apply #'vconcat seqs))
275 (`string (apply #'concat seqs))
276 (`list (apply #'append (append seqs '(nil))))
277 (t (error "Not a sequence type name: %S" type))))
278
279 (defun seq-mapcat (function seq &optional type)
280 "Concatenate the result of applying FUNCTION to each element of SEQ.
281 The result is a sequence of type TYPE, or a list if TYPE is nil."
282 (apply #'seq-concatenate (or type 'list)
283 (seq-map function seq)))
284
285 (defun seq-partition (seq n)
286 "Return a list of the elements of SEQ grouped into sub-sequences of length N.
287 The last sequence may contain less than N elements. If N is a
288 negative integer or 0, nil is returned."
289 (unless (< n 1)
290 (let ((result '()))
291 (while (not (seq-empty-p seq))
292 (push (seq-take seq n) result)
293 (setq seq (seq-drop seq n)))
294 (nreverse result))))
295
296 (defun seq-intersection (seq1 seq2 &optional testfn)
297 "Return a list of the elements that appear in both SEQ1 and SEQ2.
298 Equality is defined by TESTFN if non-nil or by `equal' if nil."
299 (seq-reduce (lambda (acc elt)
300 (if (seq-contains seq2 elt testfn)
301 (cons elt acc)
302 acc))
303 (seq-reverse seq1)
304 '()))
305
306 (defun seq-difference (seq1 seq2 &optional testfn)
307 "Return a list of the elements that appear in SEQ1 but not in SEQ2.
308 Equality is defined by TESTFN if non-nil or by `equal' if nil."
309 (seq-reduce (lambda (acc elt)
310 (if (not (seq-contains seq2 elt testfn))
311 (cons elt acc)
312 acc))
313 (seq-reverse seq1)
314 '()))
315
316 (defun seq-group-by (function seq)
317 "Apply FUNCTION to each element of SEQ.
318 Separate the elements of SEQ into an alist using the results as
319 keys. Keys are compared using `equal'."
320 (seq-reduce
321 (lambda (acc elt)
322 (let* ((key (funcall function elt))
323 (cell (assoc key acc)))
324 (if cell
325 (setcdr cell (push elt (cdr cell)))
326 (push (list key elt) acc))
327 acc))
328 (seq-reverse seq)
329 nil))
330
331 (defalias 'seq-reverse
332 (if (ignore-errors (reverse [1 2]))
333 #'reverse
334 (lambda (seq)
335 "Return the reversed copy of list, vector, or string SEQ.
336 See also the function `nreverse', which is used more often."
337 (let ((result '()))
338 (seq-map (lambda (elt) (push elt result))
339 seq)
340 (if (listp seq)
341 result
342 (seq-into result (type-of seq)))))))
343
344 (defun seq-into (seq type)
345 "Convert the sequence SEQ into a sequence of type TYPE.
346 TYPE can be one of the following symbols: vector, string or list."
347 (pcase type
348 (`vector (vconcat seq))
349 (`string (concat seq))
350 (`list (append seq nil))
351 (t (error "Not a sequence type name: %S" type))))
352
353 (defun seq-min (seq)
354 "Return the smallest element of SEQ.
355 SEQ must be a sequence of numbers or markers."
356 (apply #'min (seq-into seq 'list)))
357
358 (defun seq-max (seq)
359 "Return the largest element of SEQ.
360 SEQ must be a sequence of numbers or markers."
361 (apply #'max (seq-into seq 'list)))
362
363 (defun seq--drop-list (list n)
364 "Return a list from LIST without its first N elements.
365 This is an optimization for lists in `seq-drop'."
366 (while (and list (> n 0))
367 (setq list (cdr list)
368 n (1- n)))
369 list)
370
371 (defun seq--take-list (list n)
372 "Return a list from LIST made of its first N elements.
373 This is an optimization for lists in `seq-take'."
374 (let ((result '()))
375 (while (and list (> n 0))
376 (setq n (1- n))
377 (push (pop list) result))
378 (nreverse result)))
379
380 (defun seq--drop-while-list (pred list)
381 "Return a list from the first element for which (PRED element) is nil in LIST.
382 This is an optimization for lists in `seq-drop-while'."
383 (while (and list (funcall pred (car list)))
384 (setq list (cdr list)))
385 list)
386
387 (defun seq--take-while-list (pred list)
388 "Return the successive elements for which (PRED element) is non-nil in LIST.
389 This is an optimization for lists in `seq-take-while'."
390 (let ((result '()))
391 (while (and list (funcall pred (car list)))
392 (push (pop list) result))
393 (nreverse result)))
394
395 (defun seq--count-successive (pred seq)
396 "Return the number of successive elements for which (PRED element) is non-nil in SEQ."
397 (let ((n 0)
398 (len (seq-length seq)))
399 (while (and (< n len)
400 (funcall pred (seq-elt seq n)))
401 (setq n (+ 1 n)))
402 n))
403
404 (defun seq--make-pcase-bindings (args)
405 "Return a list of bindings of the variables in ARGS to the elements of a sequence."
406 (let ((bindings '())
407 (index 0)
408 (rest-marker nil))
409 (seq-doseq (name args)
410 (unless rest-marker
411 (pcase name
412 (`&rest
413 (progn (push `(app (pcase--flip seq-drop ,index)
414 ,(seq--elt-safe args (1+ index)))
415 bindings)
416 (setq rest-marker t)))
417 (t
418 (push `(app (pcase--flip seq--elt-safe ,index) ,name) bindings))))
419 (setq index (1+ index)))
420 bindings))
421
422 (defun seq--make-pcase-patterns (args)
423 "Return a list of `(seq ...)' pcase patterns from the argument list ARGS."
424 (cons 'seq
425 (seq-map (lambda (elt)
426 (if (seq-p elt)
427 (seq--make-pcase-patterns elt)
428 elt))
429 args)))
430
431 ;; Helper function for the Backward-compatible version of `seq-let'
432 ;; for Emacs<25.1.
433 (defun seq--make-bindings (args seq &optional bindings)
434 "Return a list of bindings of the variables in ARGS to the elements of a sequence.
435 if BINDINGS is non-nil, append new bindings to it, and return
436 BINDINGS."
437 (let ((index 0)
438 (rest-marker nil))
439 (seq-doseq (name args)
440 (unless rest-marker
441 (pcase name
442 ((pred seq-p)
443 (setq bindings (seq--make-bindings (seq--elt-safe args index)
444 `(seq--elt-safe ,seq ,index)
445 bindings)))
446 (`&rest
447 (progn (push `(,(seq--elt-safe args (1+ index))
448 (seq-drop ,seq ,index))
449 bindings)
450 (setq rest-marker t)))
451 (t
452 (push `(,name (seq--elt-safe ,seq ,index)) bindings))))
453 (setq index (1+ index)))
454 bindings))
455
456 (defun seq--elt-safe (seq n)
457 "Return element of SEQ at the index N.
458 If no element is found, return nil."
459 (when (or (listp seq)
460 (and (sequencep seq)
461 (> (seq-length seq) n)))
462 (seq-elt seq n)))
463
464 (defun seq--activate-font-lock-keywords ()
465 "Activate font-lock keywords for some symbols defined in seq."
466 (font-lock-add-keywords 'emacs-lisp-mode
467 '("\\<seq-doseq\\>" "\\<seq-let\\>")))
468
469 (defalias 'seq-copy #'copy-sequence)
470 (defalias 'seq-elt #'elt)
471 (defalias 'seq-length #'length)
472 (defalias 'seq-do #'mapc)
473 (defalias 'seq-each #'seq-do)
474 (defalias 'seq-map #'mapcar)
475 (defalias 'seq-p #'sequencep)
476
477 (unless (fboundp 'elisp--font-lock-flush-elisp-buffers)
478 ;; In Emacsā‰„25, (via elisp--font-lock-flush-elisp-buffers and a few others)
479 ;; we automatically highlight macros.
480 (add-hook 'emacs-lisp-mode-hook #'seq--activate-font-lock-keywords))
481
482 (provide 'seq)
483 ;;; seq.el ends here