Emacs Lisp: Sequence Iteration

By Xah Lee. Date: . Last updated: .

Map: mapcar

mapcar
(mapcar FUNCTION SEQUENCE)
  • Apply function to each element of Sequence
  • Return the result as a list.
  • SEQUENCE may be a list, vector, string.
  • FUNCTION must be a Symbol, or Lambda.
;; apply the function car to each sublist (take 1st element)
(equal
 (mapcar 'car '((1 2) (3 4) (5 6)))
 '(1 3 5))

;; apply a lambda to each vector (take 1st element)
(equal
 (mapcar (lambda (x) (aref x 0)) [[1 2] [3 4] [5 6]])
 '(1 3 5))

;; apply the function 1+ to each vector element
(equal
 (mapcar '1+ [0 1 2])
 '(1 2 3))

mapc (for-each)

mapc
(mapc FUNCTION SEQUENCE)
  • Apply function to each element of Sequence
  • Return SEQUENCE unchanged.

Tip: this is used for side-effect only. e.g. for FUNCTION to print things.

(mapc
 (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"))

dolist: Loop Thru a List

dolist
  • (dolist (VAR LIST) BODY)
  • (dolist (VAR LIST RESULT) BODY)
  • Loop over a list.
  • Each time eval BODY, with VAR having value of an element in list.
  • Return nil or RESULT.
  • RESULT is evaluated last.

Tip: this is used for side-effect only.

(let (xx)
  (setq xx (number-sequence 1 5))
  (dolist (n xx)
    (insert (number-to-string n))))

;; inserts 12345
;; return nil

Exit Loop/Iteration

Lisp Data Structure

List

Vector

Sequence (List, Vector)

Hash Table

Emacs Lisp: Loop and Iteration