マッピング関数は、リストやベクトル、文字列などのシーケンスの各要素に対して、指定された関数(特殊な形式やマクロではないもの)を適用します(シーケンス、配列、ベクトルを参照)。Emacs
Lispにはこのような関数がいくつかあり、本節ではシーケンスをマッピングするmapcar、mapc、mapconcat、およびmapcanについて説明します。obarray内のシンボルをマッピングする関数mapatomsについては、mapatomsの定義を参照してください。ハッシュテーブル内のキー/値の関連付けをマッピングする関数maphashについては、maphashの定義を参照してください。
これらのマッピング関数はchar-tableでは動作しません。char-tableは疎な配列であり、その名目上のインデックス範囲が非常に大きいためです。char-tableの疎な性質を適切に考慮してマッピングを行うには、関数
map-char-table を使用してください(Char-Tables を参照)。
mapcar は sequence
の各要素に対して順に function を適用し、その結果のリストを返します。
引数 sequence には、文字テーブル以外のあらゆる種類のシーケンス(すなわち、リスト、ベクトル、bool-vector、または文字列)が指定可能です。結果は常にリストとなります。結果の長さは sequence の長さと同じです。例えば:
(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))
この関数は、mapcarと同様にsequenceの各要素にfunctionを適用しますが、その結果をリストにまとめるのではなく、結果(リストである必要があります)を変更することで(nconcを使用。リストを再配置する関数を参照)、結果のすべての要素を含む単一のリストを返します。mapcarと同様に、sequenceはchar-table以外の任意の型を指定できます。
;; Contrast this: (mapcar #'list '(a b c d)) ⇒ ((a) (b) (c) (d)) ;; with this: (mapcan #'list '(a b c d)) ⇒ (a b c d)
mapc は mapcar
と同様ですが、function
は副作用にのみ使用されます—これが返す値は無視され、リストに収集されることもありません。 mapc は常に sequence を返します。
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; a nil value is treated as the
empty string. See Sequences, Arrays, and Vectors.
引数 function は、1つの引数を受け取り、文字のシーケンス(文字列、ベクトル、またはリスト)を返す関数である必要があります。引数 sequence は、char-table を除くあらゆる種類のシーケンス、すなわちリスト、ベクトル、bool-vector、または文字列であることができます。
(mapconcat #'symbol-name
'(The cat in the hat)
" ")
⇒ "The cat in the hat"
(mapconcat (lambda (x) (format "%c" (1+ x)))
"HAL-8000")
⇒ "IBM.9111"