ELisp: 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 / Modify Items (At Arbitrary Positions)

💡 TIP: this is the most general function, that you can have a function go thru each item, delete it by returning nil, or add more items by returning a list, or change it by returning a list of one item. This is more general than map because map cannot delete items, and more general than filter because filter cannot add item nor transform the items you want.

;; 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 ELisp: 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 ELisp: 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 ELisp: Destructure Binding]

Misc

complete list

Reference

Emacs Lisp, Functions on Sequence

Emacs Lisp, Vector