Elisp: Sequence. Sort, Reverse
sort
sort-
(sort SEQ &key KEY LESSP REVERSE IN-PLACE)major change in Emacs 30 (date 2025)
Optional arguments are keyword argument pairs.
:key FUNC→ FUNC is a function. It is given one element from SEQ. Return value is used for comparison. If nil,identityis used.:lessp FUNC→ FUNC is a function that takes two args and returns true if they are in order. If nil,value<is used.:reverse BOOL→ if BOOL is true, the sorting order implied by FUNC is reversed.:in-place BOOL→ if BOOL is true, SEQ is sorted in-place and returned. Default is false.
For compatibility, the calling convention (sort SEQ LESSP) can also be used; in this case, sorting is always done in-place.
(setq xx (list 2 3 1)) (sort xx ) ;; (1 2 3) (setq xx (vector ["b" 1] ["c" 3] ["a" 2])) ;; sort by second column (sort xx :key (lambda (x) (aref x 1))) ;; [["b" 1] ["a" 2] ["c" 3]] ;; sort normally, by first column (sort xx ) ;; [["a" 2] ["b" 1] ["c" 3]]
before emacs 30:
(sort SEQ PREDICATE)(setq xx (list 2 4 1 9 5)) (sort xx '>) ;; (9 5 4 2 1) xx ;; (9 5 4 2 1) ;; note, the original list may be destroyed
seq-sort-
(seq-sort PRED SEQUENCE)- sort a Sequence
- original unchanged.
(setq xx (list 2 4 1 9 5)) (seq-sort '> xx) ;; (9 5 4 2 1) xx ;; (2 4 1 9 5) ;; original unchanged seq-sort-by-
(seq-sort-by FUNCTION PRED SEQUENCE)Sort sequence, by the value of a function applied to each element.
FUNCTION takes one arg.
(setq xx (list "a-9" "b-3" "c-2" )) ;; sort by the number in the string (seq-sort-by (lambda (x) (string-to-number (substring x 2))) '< xx) ;; ("c-2" "b-3" "a-9") xx ;; ("a-9" "b-3" "c-2")
Reverse
nreverse→ reverse but original is destroyed.reverse→ reverse sequenceseq-reverse→ similar toreverse, but can work on user-created sequence type.
;; example showing how nreverse destroys the original value (setq xx (number-sequence 1 5)) (setq yy (nreverse xx)) xx ;; (1) yy ;; (5 4 3 2 1)
Elisp, sequence functions
- Elisp: Sequence Type
- Elisp: Sequence Functions
- Elisp: Sequence. Take, Drop, Slice
- Elisp: Sequence. Iteration Guide
- Elisp: Sequence. Map
- Elisp: Sequence. Foreach
- Elisp: Sequence. some, every (conditional exit)
- Elisp: Sequence. Filter
- Elisp: Sequence. Insert or Remove
- Elisp: Sequence. Find
- Elisp: Sequence. Sort, Reverse
- Elisp: Sequence. Join, Convert
- Elisp: Sequence. Union, Intersection, Difference
- Elisp: Sequence. Partition, Group
- Elisp: Sequence. Min, Max, Random
- Elisp: Destructure Binding (seq-setq, seq-let)