在LISP中定义一个加法函数
(defun my-add (x y) (+ x y))
但是,调用者可以输入任意类型的参数,导致异常。大部分情况下,调用者知道该输入什么
类型的参数,但是,某些情况下需要函数内部校验输入参数的类型。
这时就该使用 type-of 函数,type-of的返回值还真复杂,使用时要特别小心。
(type-of '()) => NULL
(type-of t) => BOOLEAN
(type-of 'a) => SYMBOL
(type-of 0) => BIT
(type-of 1) => BIT
(type-of 2) => (INTEGER 0 16777215)
(type-of -1) => (INTEGER -16777216 (0))
(type-of 0.0) => SINGLE-FLOAT
(type-of #\a) => STANDARD-CHAR
(type-of "abc") => (SIMPLE-BASE-STRING 5)
(type-of #'sin) => COMPILED-FUNCTION
(type-of #'(lambda(x) (+ 1 x))) => FUNCTION
(type-of '(a b c)) => CONS
(type-of (cons 'a 'b)) => CONS
(type-of (make-hash-table)) => HASH-TABLE
(type-of (make-array 3)) => (SIMPLE-VECTOR 3)
(type-of (make-array '(3 4)))=> (SIMPLE-ARRAY T (3 4))
(type-of (open "test.txt")) => FILE-STREAM
(type-of (defpackage fff)) => PACKAGE
(type-of (/ 1 2)) => RATIO
(type-of #c(2 1)) => COMPLEX
例如,判断一个参数是不是哈希表
(eq 'hash-table (type-of x))
上面的写法有点硬编码的坏味道,总感觉和CLisp的实现版本有关,或许可以这样写
(eq (make-hash-table) (type-of x))