LISP动态定义函数 [英] LISP dynamically define functions

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

问题描述



不工作的例子:

 (DEFUN自定义(name op const var)
(DEFUN name(var)(op const var)))

问题在于名称未经过计算,因此定义的函数始终称为名称。



我知道 FUNCALL APPLY 可以动态地评估参数,但我不知道如何正确调用 FUNCALL DEFUN ...

解决方案

我不认为您可以使用嵌套defuns。



您可以使用 defun 返回 lambda

 (defun custo m(op const)
(lambda(arg)(funcall op const arg)))

然后使用 fdefinition

 (setf(fdefinition'+42)(custom'+ '42))
code>

或者使用

 ( defmacro custom(name op const)
(let((arg(gensym)))
`(defun,name(,arg)
(,op,const,arg))))

(自定义+42 + 42)

PS。我想你需要解释为什么你要这样做,那么我们将能够更好地解释你的选择。


I want to define a function with a parameter that defines another function with that parameter as the name.

example that dont work:

(DEFUN custom (name op const var)
  (DEFUN name (var) (op const var)))

The problem is that name isnt evaluated and so the function that is defined is always called name.

I know that FUNCALL and APPLY can evaluate parameter dynamically, but i don't know how to call FUNCALL DEFUN... correctly.

解决方案

I don't think you can use nested defuns.

You can either use a defun to return a lambda:

(defun custom (op const) 
  (lambda (arg) (funcall op const arg)))

and then use fdefinition:

(setf (fdefinition '+42) (custom '+ '42))

or use defmacro:

(defmacro custom (name op const)
  (let ((arg (gensym)))
    `(defun ,name (,arg)
       (,op ,const ,arg))))

(custom +42 + 42)

PS. I think you need to explain why you are trying to do this, then we will be able to explain your options better.

这篇关于LISP动态定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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