我一直在进行遗传编程,根据函数的arity将函数分成不同的函数集; 这是非常复杂的。
我想知道是否有更简单的方法来做到这一点。例如,是否有一个函数可以返回给定函数的arity。
提前致谢。
我一直在进行遗传编程,根据函数的arity将函数分成不同的函数集; 这是非常复杂的。
我想知道是否有更简单的方法来做到这一点。例如,是否有一个函数可以返回给定函数的arity。
提前致谢。
对于解释函数,您应该能够使用function-lambda-expression
。
对于编译函数,不幸的是,这个函数通常返回nil
,因此您将需要使用一个依赖于实现的函数(clocc/port/sys.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)))
arglist
函数返回参数函数的lambda列表而不是一个数字。(defun arity (fn)
(let ((arglist (arglist fn)))
(if (intersection arglist lambda-list-keywords)
(error "~S lambda list ~S contains keywords" fn arglist)
(length arglist))))
有一个便携式的库可以提供函数的lambda列表:https://github.com/Shinmera/trivial-arguments
(ql:quickload "trivial-arguments")
例子:
(arg:arglist #'gethash)
;; => (sb-impl::key hash-table &optional sb-impl::default)
(defun foo (a b c &optional d) nil)
(arglist #'foo) ;; => (a b c &optional d)