* lisp/emacs-lisp/seq.el (seq--make-bindings): Improve the docstring.
[emacs.git] / lisp / emacs-lisp / seq.el
blobea7a61382e1a3904dc560bf2d0b1f69745311825
1 ;;; seq.el --- Sequence manipulation functions -*- lexical-binding: t -*-
3 ;; Copyright (C) 2014-2015 Free Software Foundation, Inc.
5 ;; Author: Nicolas Petton <nicolas@petton.fr>
6 ;; Keywords: sequences
7 ;; Version: 1.6
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 ;; All functions are tested in test/automated/seq-tests.el
43 ;;; TODO:
45 ;; - Add support for &rest in the argument list of seq-let
47 ;;; Code:
49 (defmacro seq-doseq (spec &rest body)
50 "Loop over a sequence.
51 Similar to `dolist' but can be applied to lists, strings, and vectors.
53 Evaluate BODY with VAR bound to each element of SEQ, in turn.
55 \(fn (VAR SEQ) BODY...)"
56 (declare (indent 1) (debug ((symbolp form &optional form) body)))
57 (let ((length (make-symbol "length"))
58 (seq (make-symbol "seq"))
59 (index (make-symbol "index")))
60 `(let* ((,seq ,(cadr spec))
61 (,length (if (listp ,seq) nil (seq-length ,seq)))
62 (,index (if ,length 0 ,seq)))
63 (while (if ,length
64 (< ,index ,length)
65 (consp ,index))
66 (let ((,(car spec) (if ,length
67 (prog1 (seq-elt ,seq ,index)
68 (setq ,index (+ ,index 1)))
69 (pop ,index))))
70 ,@body)))))
72 (defmacro seq-let (args seq &rest body)
73 "Bind the variables in ARGS to the elements of SEQ then evaluate BODY."
74 (declare (indent 2) (debug t))
75 (let ((seq-var (make-symbol "seq")))
76 `(let* ((,seq-var ,seq)
77 ,@(seq--make-bindings args seq-var))
78 ,@body)))
80 (defun seq-drop (seq n)
81 "Return a subsequence of SEQ without its first N elements.
82 The result is a sequence of the same type as SEQ.
84 If N is a negative integer or zero, SEQ is returned."
85 (if (<= n 0)
86 seq
87 (if (listp seq)
88 (seq--drop-list seq n)
89 (let ((length (seq-length seq)))
90 (seq-subseq seq (min n length) length)))))
92 (defun seq-take (seq n)
93 "Return a subsequence of SEQ with its first N elements.
94 The result is a sequence of the same type as SEQ.
96 If N is a negative integer or zero, an empty sequence is
97 returned."
98 (if (listp seq)
99 (seq--take-list seq n)
100 (seq-subseq seq 0 (min (max n 0) (seq-length seq)))))
102 (defun seq-drop-while (pred seq)
103 "Return a sequence from the first element for which (PRED element) is nil in SEQ.
104 The result is a sequence of the same type as SEQ."
105 (if (listp seq)
106 (seq--drop-while-list pred seq)
107 (seq-drop seq (seq--count-successive pred seq))))
109 (defun seq-take-while (pred seq)
110 "Return the successive elements for which (PRED element) is non-nil in SEQ.
111 The result is a sequence of the same type as SEQ."
112 (if (listp seq)
113 (seq--take-while-list pred seq)
114 (seq-take seq (seq--count-successive pred seq))))
116 (defun seq-filter (pred seq)
117 "Return a list of all the elements for which (PRED element) is non-nil in SEQ."
118 (let ((exclude (make-symbol "exclude")))
119 (delq exclude (seq-map (lambda (elt)
120 (if (funcall pred elt)
122 exclude))
123 seq))))
125 (defun seq-remove (pred seq)
126 "Return a list of all the elements for which (PRED element) is nil in SEQ."
127 (seq-filter (lambda (elt) (not (funcall pred elt)))
128 seq))
130 (defun seq-reduce (function seq initial-value)
131 "Reduce the function FUNCTION across SEQ, starting with INITIAL-VALUE.
133 Return the result of calling FUNCTION with INITIAL-VALUE and the
134 first element of SEQ, then calling FUNCTION with that result and
135 the second element of SEQ, then with that result and the third
136 element of SEQ, etc.
138 If SEQ is empty, return INITIAL-VALUE and FUNCTION is not called."
139 (if (seq-empty-p seq)
140 initial-value
141 (let ((acc initial-value))
142 (seq-doseq (elt seq)
143 (setq acc (funcall function acc elt)))
144 acc)))
146 (defun seq-some-p (pred seq)
147 "Return any element for which (PRED element) is non-nil in SEQ, nil otherwise."
148 (catch 'seq--break
149 (seq-doseq (elt seq)
150 (when (funcall pred elt)
151 (throw 'seq--break elt)))
152 nil))
154 (defun seq-every-p (pred seq)
155 "Return non-nil if (PRED element) is non-nil for all elements of the sequence SEQ."
156 (catch 'seq--break
157 (seq-doseq (elt seq)
158 (or (funcall pred elt)
159 (throw 'seq--break nil)))
162 (defun seq-count (pred seq)
163 "Return the number of elements for which (PRED element) is non-nil in SEQ."
164 (let ((count 0))
165 (seq-doseq (elt seq)
166 (when (funcall pred elt)
167 (setq count (+ 1 count))))
168 count))
170 (defun seq-empty-p (seq)
171 "Return non-nil if the sequence SEQ is empty, nil otherwise."
172 (if (listp seq)
173 (null seq)
174 (= 0 (seq-length seq))))
176 (defun seq-sort (pred seq)
177 "Return a sorted sequence comparing using PRED the elements of SEQ.
178 The result is a sequence of the same type as SEQ."
179 (if (listp seq)
180 (sort (seq-copy seq) pred)
181 (let ((result (seq-sort pred (append seq nil))))
182 (seq-into result (type-of seq)))))
184 (defun seq-contains-p (seq elt &optional testfn)
185 "Return the first element in SEQ that equals to ELT.
186 Equality is defined by TESTFN if non-nil or by `equal' if nil."
187 (seq-some-p (lambda (e)
188 (funcall (or testfn #'equal) elt e))
189 seq))
191 (defun seq-uniq (seq &optional testfn)
192 "Return a list of the elements of SEQ with duplicates removed.
193 TESTFN is used to compare elements, or `equal' if TESTFN is nil."
194 (let ((result '()))
195 (seq-doseq (elt seq)
196 (unless (seq-contains-p result elt testfn)
197 (setq result (cons elt result))))
198 (nreverse result)))
200 (defun seq-subseq (seq start &optional end)
201 "Return the subsequence of SEQ from START to END.
202 If END is omitted, it defaults to the length of the sequence.
203 If START or END is negative, it counts from the end."
204 (cond ((or (stringp seq) (vectorp seq)) (substring seq start end))
205 ((listp seq)
206 (let (len (errtext (format "Bad bounding indices: %s, %s" start end)))
207 (and end (< end 0) (setq end (+ end (setq len (seq-length seq)))))
208 (if (< start 0) (setq start (+ start (or len (setq len (seq-length seq))))))
209 (when (> start 0)
210 (setq seq (nthcdr (1- start) seq))
211 (or seq (error "%s" errtext))
212 (setq seq (cdr seq)))
213 (if end
214 (let ((res nil))
215 (while (and (>= (setq end (1- end)) start) seq)
216 (push (pop seq) res))
217 (or (= (1+ end) start) (error "%s" errtext))
218 (nreverse res))
219 (seq-copy seq))))
220 (t (error "Unsupported sequence: %s" seq))))
222 (defun seq-concatenate (type &rest seqs)
223 "Concatenate, into a sequence of type TYPE, the sequences SEQS.
224 TYPE must be one of following symbols: vector, string or list.
226 \n(fn TYPE SEQUENCE...)"
227 (pcase type
228 (`vector (apply #'vconcat seqs))
229 (`string (apply #'concat seqs))
230 (`list (apply #'append (append seqs '(nil))))
231 (t (error "Not a sequence type name: %S" type))))
233 (defun seq-mapcat (function seq &optional type)
234 "Concatenate the result of applying FUNCTION to each element of SEQ.
235 The result is a sequence of type TYPE, or a list if TYPE is nil."
236 (apply #'seq-concatenate (or type 'list)
237 (seq-map function seq)))
239 (defun seq-partition (seq n)
240 "Return a list of the elements of SEQ grouped into sub-sequences of length N.
241 The last sequence may contain less than N elements. If N is a
242 negative integer or 0, nil is returned."
243 (unless (< n 1)
244 (let ((result '()))
245 (while (not (seq-empty-p seq))
246 (push (seq-take seq n) result)
247 (setq seq (seq-drop seq n)))
248 (nreverse result))))
250 (defun seq-intersection (seq1 seq2 &optional testfn)
251 "Return a list of the elements that appear in both SEQ1 and SEQ2.
252 Equality is defined by TESTFN if non-nil or by `equal' if nil."
253 (seq-reduce (lambda (acc elt)
254 (if (seq-contains-p seq2 elt testfn)
255 (cons elt acc)
256 acc))
257 (seq-reverse seq1)
258 '()))
260 (defun seq-difference (seq1 seq2 &optional testfn)
261 "Return a list of th elements that appear in SEQ1 but not in SEQ2.
262 Equality is defined by TESTFN if non-nil or by `equal' if nil."
263 (seq-reduce (lambda (acc elt)
264 (if (not (seq-contains-p seq2 elt testfn))
265 (cons elt acc)
266 acc))
267 (seq-reverse seq1)
268 '()))
270 (defun seq-group-by (function seq)
271 "Apply FUNCTION to each element of SEQ.
272 Separate the elements of SEQ into an alist using the results as
273 keys. Keys are compared using `equal'."
274 (seq-reduce
275 (lambda (acc elt)
276 (let* ((key (funcall function elt))
277 (cell (assoc key acc)))
278 (if cell
279 (setcdr cell (push elt (cdr cell)))
280 (push (list key elt) acc))
281 acc))
282 (seq-reverse seq)
283 nil))
285 (defalias 'seq-reverse
286 (if (ignore-errors (reverse [1 2]))
287 #'reverse
288 (lambda (seq)
289 "Return the reversed copy of list, vector, or string SEQ.
290 See also the function `nreverse', which is used more often."
291 (let ((result '()))
292 (seq-map (lambda (elt) (push elt result))
293 seq)
294 (if (listp seq)
295 result
296 (seq-into result (type-of seq)))))))
298 (defun seq-into (seq type)
299 "Convert the sequence SEQ into a sequence of type TYPE.
300 TYPE can be one of the following symbols: vector, string or list."
301 (pcase type
302 (`vector (vconcat seq))
303 (`string (concat seq))
304 (`list (append seq nil))
305 (t (error "Not a sequence type name: %S" type))))
307 (defun seq--drop-list (list n)
308 "Return a list from LIST without its first N elements.
309 This is an optimization for lists in `seq-drop'."
310 (while (and list (> n 0))
311 (setq list (cdr list)
312 n (1- n)))
313 list)
315 (defun seq--take-list (list n)
316 "Return a list from LIST made of its first N elements.
317 This is an optimization for lists in `seq-take'."
318 (let ((result '()))
319 (while (and list (> n 0))
320 (setq n (1- n))
321 (push (pop list) result))
322 (nreverse result)))
324 (defun seq--drop-while-list (pred list)
325 "Return a list from the first element for which (PRED element) is nil in LIST.
326 This is an optimization for lists in `seq-drop-while'."
327 (while (and list (funcall pred (car list)))
328 (setq list (cdr list)))
329 list)
331 (defun seq--take-while-list (pred list)
332 "Return the successive elements for which (PRED element) is non-nil in LIST.
333 This is an optimization for lists in `seq-take-while'."
334 (let ((result '()))
335 (while (and list (funcall pred (car list)))
336 (push (pop list) result))
337 (nreverse result)))
339 (defun seq--count-successive (pred seq)
340 "Return the number of successive elements for which (PRED element) is non-nil in SEQ."
341 (let ((n 0)
342 (len (seq-length seq)))
343 (while (and (< n len)
344 (funcall pred (seq-elt seq n)))
345 (setq n (+ 1 n)))
348 (defun seq--activate-font-lock-keywords ()
349 "Activate font-lock keywords for some symbols defined in seq."
350 (font-lock-add-keywords 'emacs-lisp-mode
351 '("\\<seq-doseq\\>" "\\<seq-let\\>")))
353 (defun seq--make-bindings (args seq &optional initial-bindings)
354 "Return an alist of bindings of the variables in ARGS to the elements of SEQ.
355 if INITIAL-BINDINGS is non-nil, append new bindings to it, and
356 return INITIAL-BINDINGS."
357 (let ((index 0))
358 (seq-doseq (name args)
359 (if (sequencep name)
360 (setq initial-bindings (seq--make-bindings
361 (seq--elt-safe args index)
362 `(seq--elt-safe ,seq ,index)
363 initial-bindings))
364 (push `(,name (seq--elt-safe ,seq ,index)) initial-bindings))
365 (setq index (1+ index)))
366 initial-bindings))
368 (defun seq--elt-safe (seq n)
369 "Return element of SEQ at the index N.
370 If no element is found, return nil."
371 (when (or (listp seq)
372 (and (sequencep seq)
373 (> (seq-length seq) n)))
374 (seq-elt seq n)))
376 (defalias 'seq-copy #'copy-sequence)
377 (defalias 'seq-elt #'elt)
378 (defalias 'seq-length #'length)
379 (defalias 'seq-do #'mapc)
380 (defalias 'seq-each #'seq-do)
381 (defalias 'seq-map #'mapcar)
383 (unless (fboundp 'elisp--font-lock-flush-elisp-buffers)
384 ;; In Emacsā‰„25, (via elisp--font-lock-flush-elisp-buffers and a few others)
385 ;; we automatically highlight macros.
386 (add-to-list 'emacs-lisp-mode-hook #'seq--activate-font-lock-keywords))
388 (provide 'seq)
389 ;;; seq.el ends here