如何修改Common Lisp中函数的绑定? [英] How can I modify function bindings in Common Lisp?

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

问题描述

下面是你可以做的方案:

Here is something you can do in Scheme:

> (define (sum lst acc)
    (if (null? lst)
        acc
        (sum (cdr lst) (+ acc (car lst)))))
> (define sum-original sum)
> (define (sum-debug lst acc)
    (print lst)
    (print acc)
    (sum-original lst acc))
> (sum '(1 2 3) 0)
6
> (set! sum sum-debug)
> (sum '(1 2 3) 0)
(1 2 3)
0
(2 3)
1
(3)
3
()
6
6
> (set! sum sum-original)
> (sum '(1 2 3) 0)
6

如果我是做Common Lisp中的以下内容:

If I were to do the following in Common Lisp:

> (defun sum (lst acc)
    (if lst
        (sum (cdr lst) (+ acc (car lst)))
        acc))
SUM
> (defvar sum-original #'sum)
SUM-ORIGINAL
> (defun sum-debug (lst acc)
    (print lst)
    (print acc)
    (funcall sum-original lst acc))
SUM-DEBUG
> (sum '(1 2 3) 0)
6

现在我该怎么办类似(SETF总和#'之和调试),将改变以 defun函数<定义的函数的结合/ code>?

Now how can I do something like (setf sum #'sum-debug) that would change the binding of a function defined with defun?

推荐答案

由于Common Lisp的有功能不同的命名空间,你需要使用符号功能 fdefinition

Because Common Lisp has a different namespace for functions, you need to use symbol-function or fdefinition.

CL-USER> (defun foo (a)
           (+ 2 a))
FOO
CL-USER> (defun debug-foo (a)
           (format t " DEBUGGING FOO: ~a" a)
           (+ 2 a))
DEBUG-FOO
CL-USER> (defun debug-foo-again (a)
           (format t " DEBUGGING ANOTHER FOO: ~a" a)
           (+ 2 a))
DEBUG-FOO-AGAIN
CL-USER> (foo 4)
6
CL-USER> (setf (symbol-function 'foo) #'debug-foo)
#<FUNCTION DEBUG-FOO>
CL-USER> (foo 4)
 DEBUGGING FOO: 4
6
CL-USER> (setf (fdefinition 'foo) #'debug-foo-again)
#<FUNCTION DEBUG-FOO-AGAIN>
CL-USER> (foo 4)
 DEBUGGING ANOTHER FOO: 4
6
CL-USER>

这篇关于如何修改Common Lisp中函数的绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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