在Common Lisp中查找函数的Arity [英] Find function's arity in Common Lisp

查看:72
本文介绍了在Common Lisp中查找函数的Arity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在做一些遗传编程,并且根据功能的不同将功能分为不同的功能集;

I've been doing some Genetic Programming and I've been separating functions into different function sets based on their arity; it's all rather complex.

我想知道是否有更简单的方法来做到这一点。例如,如果有一个函数返回给定函数的arity。

I'd like to know if there's a simpler way to to do it. For example, if there's a function that returns the arity of a given function.

预先加油。

推荐答案

对于解释功能,您应该可以使用 function-lambda-expression

For interpreted functions you should be able to use function-lambda-expression.

对于编译函数,a,此函数通常返回 nil ,因此您必须使用与实现相关的功能( clocc / 端口 / sys.lisp ):

For compiled functions, alas, this function often returns nil, so you will have to use an implementation-dependent function (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)))

编辑:请注意,CL中的 arity 并不是一个真正的数字,因为Lisp函数可以接受 可选 休息 关键字 参数rel = nofollow noreferrer> 必填 个;这就是为什么上面的 arglist 函数返回参数函数的lambda列表,而不是数字。

note that arity in CL is not really a number, since Lisp functions can accept optional, rest and keyword arguments in addition to required ones; this is why the above arglist function returns the lambda list of the argument function, not a number.

如果您只对仅接受必需参数的函数感兴趣,则需要使用类似的东西

If you are only interested in functions which accept only required parameters, you would need to use something like

(defun arity (fn)
  (let ((arglist (arglist fn)))
    (if (intersection arglist lambda-list-keywords)
        (error "~S lambda list ~S contains keywords" fn arglist)
        (length arglist))))

这篇关于在Common Lisp中查找函数的Arity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆