(lispref.info)Mapping Functions

Next: Anonymous Functions Prev: Calling Functions Up: Functions

Mapping Functions

   A "mapping function" applies a given function to each element of a
list or other collection.  Emacs Lisp has three such functions;
`mapcar' and `mapconcat', which scan a list, are described here.  For
the third mapping function, `mapatoms', see Note: Creating Symbols.

 - Function: mapcar FUNCTION SEQUENCE
     `mapcar' applies FUNCTION to each element of SEQUENCE in turn.
     The results are made into a `nil'-terminated list.

     The argument SEQUENCE may be a list, a 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 'char-to-string "abc")
               => ("a" "b" "c")

          ;; Call each function in `my-hooks'.
          (mapcar 'funcall my-hooks)

          (defun mapcar* (f &rest args)
            "Apply FUNCTION to successive cars of all ARGS, until one
          ends.  Return the list of results."
            ;; If no list is exhausted,
            (if (not (memq 'nil args))
                ;; Apply function to CARs.
                (cons (apply f (mapcar 'car args))
                      (apply 'mapcar* f
                             ;; Recurse for rest of elements.
                             (mapcar 'cdr args)))))

          (mapcar* 'cons '(a b c) '(1 2 3 4))
               => ((a . 1) (b . 2) (c . 3))

     `mapconcat' applies FUNCTION to each element of SEQUENCE: the
     results, which must be strings, are concatenated.  Between each
     pair of result strings, `mapconcat' inserts the string SEPARATOR.
     Usually SEPARATOR contains a space or comma or other suitable

     The argument FUNCTION must be a function that can take one
     argument and returns a string.

          (mapconcat 'symbol-name
                     '(The cat in the hat)
                     " ")
               => "The cat in the hat"

          (mapconcat (function (lambda (x) (format "%c" (1+ x))))
               => "IBM.9111"

automatically generated by info2www