次: , 前: Editing Types, 上: Lisp Data Types


2.5 型述語

Emacs Lispインタープリタ自身は、関数を呼び出すときに渡す実引数の 型検査を行いません。 そうできないのは、他のプログラム言語が行うようには、 Lispの関数の引数にはデータ型の宣言がないからです。 したがって、各実引数がその関数で扱える型に属するかどうかを検査するのは、 各関数の責任です。

すべての組み込み関数は、必要なときには実引数の型検査を行い、 引数が誤った型であれば、エラーwrong-type-argumentを通知します。 たとえば、+に扱えない引数を渡すと、つぎのようになります。

     (+ 2 'a)
          error--> Wrong type argument: number-or-marker-p, a

読者のプログラムで、異なる型を異なるように扱いたい場合には、 明示的に型検査を行う必要があります。 オブジェクトの型を検査するもっとも一般的な方法は、 型述語(type predicate)関数を呼び出すことです。 Emacsには、各型ごとに型述語があり、 型を組み合わせたものに対する述語もあります。

型述語関数は1つの引数を取ります。 引数が適切な型に属していればtを返し、 さもなければnilを返します。 述語関数に関するLisp一般の慣習に従って、 ほとんどの型述語の名前は`p'で終ります。

以下は、リストの検査に述語listpを使い、 シンボルの検査に述語symbolpを使う例です。

     (defun add-on (x)
       (cond ((symbolp x)
     
              ;; Xがシンボルならば、それをLISTに加える
              (setq list (cons x list)))
             ((listp x)
     
              ;; Xがリストならば、その要素をLISTに追加する
              (setq list (append x list)))
             (t
     
              ;; シンボルとリストだけを扱う
              (error "Invalid argument %s in add-on" x))))

定義済みの型述語を、アルファベット順に、参照先を併記してあげておきます。

atom
see atom。
arrayp
see arrayp。
bool-vector-p
see bool-vector-p。
bufferp
see bufferp。
byte-code-function-p
see byte-code-function-p。
case-table-p
see case-table-p。
char-or-string-p
see char-or-string-p。
char-table-p
see char-table-p。
commandp
see commandp。
consp
see consp。
display-table-p
see display-table-p。
floatp
see floatp。
frame-configuration-p
see frame-configuration-p。
frame-live-p
see frame-live-p。
framep
see framep。
functionp
see functionp。
integer-or-marker-p
see integer-or-marker-p。
integerp
see integerp。
keymapp
see keymapp。
listp
see listp。
markerp
see markerp。
wholenump
see wholenump。
nlistp
see nlistp。
numberp
see numberp。
number-or-marker-p
see number-or-marker-p。
overlayp
see overlayp。
processp
see processp。
sequencep
see sequencep。
stringp
see stringp。
subrp
see subrp。
symbolp
see symbolp。
syntax-table-p
see syntax-table-p。
user-variable-p
see user-variable-p。
vectorp
see vectorp。
window-configuration-p
see window-configuration-p。
window-live-p
see window-live-p。
windowp
see windowp。

オブジェクトの型を調べるもっとも一般的な方法は、 関数type-ofを呼び出すことです。 各オブジェクトはたった1つの基本型に属することを思い出してください。 type-ofはどの1つかを教えてくれます(see Lisp Data Types)。 しかし、type-ofは、基本型以外についてはなにも知りません。 多くの場合、type-ofより型述語を使うほうが便利でしょう。

— 機能: type-of object

この関数は、objectの基本型を示すシンボルを返す。 その値は、 symbol、 integer、float、string、cons、vector、 char-table、bool-vector、subr、 compiled-function、marker、overlay、window、 buffer、frame、process、window-configurationの シンボルのうちの1つ。

          (type-of 1)
               => integer
          (type-of 'nil)
               => symbol
          
          (type-of '())    ; ()はnil
               => symbol
          (type-of '(x))
               => cons