elisp: Mapping Functions
12.6 Mapping Functions
======================
A “mapping function” applies a given function (_not_ a special form or
macro) to each element of a list or other collection. Emacs Lisp has
several such functions; this section describes ‘mapcar’, ‘mapc’, and
‘mapconcat’, which map over a list. Definition of mapatoms, for
the function ‘mapatoms’ which maps over the symbols in an obarray.
Definition of maphash, for the function ‘maphash’ which maps
over key/value associations in a hash table.
These mapping functions do not allow char-tables because a char-table
is a sparse array whose nominal range of indices is very large. To map
over a char-table in a way that deals properly with its sparse nature,
use the function ‘map-char-table’ (Char-Tables).
-- Function: mapcar function sequence
‘mapcar’ applies FUNCTION to each element of SEQUENCE in turn, and
returns a list of the results.
The argument SEQUENCE can be any kind of sequence except a
char-table; that is, a list, a vector, a bool-vector, or a string.
The result is always a list. The length of the result is the same
as the length of SEQUENCE. For example:
(mapcar 'car '((a b) (c d) (e f)))
⇒ (a c e)
(mapcar '1+ [1 2 3])
⇒ (2 3 4)
(mapcar 'string "abc")
⇒ ("a" "b" "c")
;; Call each function in ‘my-hooks’.
(mapcar 'funcall my-hooks)
(defun mapcar* (function &rest args)
"Apply FUNCTION to successive cars of all ARGS.
Return the list of results."
;; If no list is exhausted,
(if (not (memq nil args))
;; apply function to CARs.
(cons (apply function (mapcar 'car args))
(apply 'mapcar* function
;; Recurse for rest of elements.
(mapcar 'cdr args)))))
(mapcar* 'cons '(a b c) '(1 2 3 4))
⇒ ((a . 1) (b . 2) (c . 3))
-- Function: mapc function sequence
‘mapc’ is like ‘mapcar’ except that FUNCTION is used for
side-effects only—the values it returns are ignored, not collected
into a list. ‘mapc’ always returns SEQUENCE.
-- Function: mapconcat function sequence separator
‘mapconcat’ applies FUNCTION to each element of SEQUENCE; the
results, which must be sequences of characters (strings, vectors,
or lists), are concatenated into a single string return value.
Between each pair of result sequences, ‘mapconcat’ inserts the
characters from SEPARATOR, which also must be a string, or a vector
or list of characters. Sequences Arrays Vectors.
The argument FUNCTION must be a function that can take one argument
and returns a sequence of characters: a string, a vector, or a
list. The argument SEQUENCE can be any kind of sequence except a
char-table; that is, a list, a vector, a bool-vector, or a string.
(mapconcat 'symbol-name
'(The cat in the hat)
" ")
⇒ "The cat in the hat"
(mapconcat (function (lambda (x) (format "%c" (1+ x))))
"HAL-8000"
"")
⇒ "IBM.9111"