我正在编写一个常见的lisp程序,我有一个可以包含字符串或函数的变量.我想调用函数,如果它是一个并返回该字符串.如何测试变量是否为函数?
代码到目前为止:
(defun string-or-function (var)
(if (typep var 'simple-array)
var
(if "Function equivalent of typep goes here."
(setf temp (fn-that-does-something))
(string-or-function temp)
Run Code Online (Sandbox Code Playgroud)
编辑:有效的代码:
(defun string-or-function (var)
(let ((s-or-f (type-of var)))
(if (equal s-or-f 'function)
(print "function")
(if (equal (car s-or-f) 'simple-array)
(print "string")))))
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?
Common Lisp有一个预测型系统.一个值具有"主体"类型的概念在Lisp中没有那么多意义.该type-of
函数实际上很少被使用,因为询问"X的类型是什么"并且更有意义地问"Y是X的类型"是没有意义的.这可以通过typep
,或者在您的情况下更简洁地完成typecase
,这只是类型的案例陈述.
(defun string-or-function (var)
(typecase var
(string (format t "string"))
(function (format t "function"))
(t (format t "something else"))))
Run Code Online (Sandbox Code Playgroud)