Emacs Lisp: Sequence Functions

By Xah Lee. Date: . Last updated: .

The Sequence library seq.el

seq.el is a library of functions on Sequence Type .

seq.el is new in Emacs 25 (Released 2016-09)

seq.el is loaded when emacs starts.

You may want to explicitly declare (require 'seq)

Some of the functions provide new functionalities, some gives a unified interface to old functions.

is Sequence, Length, Empty

Sort, Reverse

Get Nth

Min, Max

Insert / Delete Items (At Arbitrary Positions)

💡 TIP: useful for inserting items at positions determined by a function. Can also be used to delete an item by returning a empty list.

;; if an item is even, insert a extra copy
(seq-mapcat
 (lambda (x)
   (if (eq 0 (mod x 2))
       (list x x)
     (list x)
     ))
 '(1 2 3 4))
;; (1 2 2 3 4 4)

Take / Remove Elements in Sequence

Take / Remove First N

Take a Slice

Filter by Function

Delete Duplicates

Delete by Equality Test

remove
(remove x sequence)
  • Remove all x in sequence.
  • The original sequence is unchanged.
  • Returns a new sequence.
  • Comparison is done with equal. [see Emacs Lisp: Equality Test]
(setq xx '(3 4 5))
(remove 4 xx) ;; (3 5)
xx ; (3 4 5)
delete
(delete x sequence)
  • Remove all x in sequence.
  • The original sequence is destroyed if it's a list.
  • Returns a new sequence.
  • Comparison is done with equal. [see Emacs Lisp: Equality Test]
(setq xx '(3 4 5))

;; always set result to the same var. because original is usually destroyed
(setq xx (delete 4 xx)) ; (3 5)

;; on vector
(setq xx [3 4 5])
(setq xx (delete 4 xx)) ; [3 5]

Loop, Iteration

Foreach (side-effect use)

Return Changed Sequence

Return True/False

💡 TIP: these are useful as functional version of loop with break. As soon as a condition found, the loop stops.

;; demo of seq-some
(seq-some (lambda (x) (eq 5 x)) [4 5 6])
;; t

Check Existance, Count

Restructure

Copy, Join, Intersection, Difference

Sequence Binding

[see Emacs Lisp: Destructure Binding]

Misc

complete list

Reference

Emacs Lisp, Functions on Sequence

Emacs Lisp, Vector