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