我通过在此处查看此答案找到了解决此问题的方法:Find Function's Arity in common lisp,需要arglist函数来处理各种实现,请参阅arglist的实现:
;; function provided by @sds at https://stackoverflow.com/questions/15465138/find-functions-arity-in-common-lisp
(defun arglist (fn)
"Return the signature of the function."
#+allegro (excl:arglist fn)
#+clisp (sys::arglist fn)
#+(or cmu scl)
(let ((f (coerce fn 'function)))
(typecase f
(STANDARD-GENERIC-FUNCTION (pcl:generic-function-lambda-list f))
(EVAL:INTERPRETED-FUNCTION (eval:interpreted-function-arglist f))
(FUNCTION (values (read-from-string (kernel:%function-arglist f))))))
#+cormanlisp (ccl:function-lambda-list
(typecase fn (symbol (fdefinition fn)) (t fn)))
#+gcl (let ((fn (etypecase fn
(symbol fn)
(function (si:compiled-function-name fn)))))
(get fn 'si:debug))
#+lispworks (lw:function-lambda-list fn)
#+lucid (lcl:arglist fn)
#+sbcl (sb-introspect:function-lambda-list fn)
#-(or allegro clisp cmu cormanlisp gcl lispworks lucid sbcl scl)
(error 'not-implemented :proc (list 'arglist fn)))
现在我可以这样做:
(defun func1 (arg1 arg2)
())
(defun get-count-args-func (func)
(length (arglist func)))
(get-count-args-func #'func1) => 2
所以我有参数的数量,你只需要注意,如果你有一些&key
参数,&rest
或者&optional
,例如:
(defun func1 (&optional arg1 arg2)
())
(defun get-count-args-func (func)
(length (arglist func)))
(get-count-args-func #'func1) => 3
看到你得到 3,因为arglist函数正在返回:
(&OPTIONAL ARG1 ARG2)
而他只返回了所需的参数:
(ARG1 ARG2)