Emacs Lisp: Sequence Iteration

By Xah Lee. Date: . Last updated: .

Map: mapcar

Apply function to each element of Sequence , and return the result as a list.
  • SEQUENCE may be a list, vector, string.
  • FUNCTION must be a Symbol, or Lambda.
;; add 1 to each vector element
 (mapcar '1+ [0 1 2])
 '(1 2 3))

;; take first element of each sublist
 (mapcar 'car '((1 2) (3 4) (5 6)))
 '(1 3 5))

;; take first element of each sub vector
 (mapcar (lambda (x) (aref x 0)) [[1 2] [3 4] [5 6]])
 '(1 3 5))

mapc (for-each)


Like mapcar, but return nil.

 (lambda (x)
   (insert (number-to-string x)))
 (number-sequence 1 9))

;; insert 123456789
;; apply a file function to a list of files
(mapc 'my-update-footer
      (list "~/x1.html" "~/x2.html" "~/x3.html"))

dotimes: Loop Fixed Number of Times with Index

(dotimes (VAR COUNT) BODY)
Loop a certain number of times. Evaluate BODY with VAR bound to successive integers running from 0, inclusive, to COUNT, exclusive. Return nil

Tip: dotimes is useful when you need the index of a list.

(dotimes (i 4)
  (insert (number-to-string i)))
;; inserts "0123", return nil
(let ((xx [3 4 5]))
  (dotimes (i (length xx))
      (elt xx i)))))
;; inserts 345
After loop, evaluate RESULT to get the return value.

dolist: Loop Thru a List

(dolist (VAR LIST) BODY)
Loop over a list. Evaluate BODY with VAR bound to each element from LIST, return nil.
(setq xx (number-sequence 1 5))

    (n xx)
  (insert (number-to-string n)))

;; inserts 12345
;; return nil
return RESULT.

while Loop

Another common form to loop thru a list is using the while function. In each iteration, pop is used to reduce the list.

(let ((xx '(a b c)))
  (while xx
    (message "%s" (pop xx))
    (sleep-for 1)))

Example with vector:

(let (xx ii)
  (setq xx [0 1 2 3 4 5])
  (setq ii 0)

  (while (< ii (length xx))
    (insert (format "%d" (aref xx ii)))
    (setq ii (1+ ii))))

; inserts 012345

Exit Loop/Function, catch/throw

Emacs Lisp: throw, catch, exit function

Lisp Data Structure

Lisp Basics


Lisp Data Structure


Lisp Symbol

Lisp Misc

Working with Elisp