本文介绍了如何修改 Common Lisp 中的函数绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您可以在 Scheme 中执行以下操作:
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 sum #'sum-debug)
的事情来改变用 defun
定义的函数的绑定?
Now how can I do something like (setf sum #'sum-debug)
that would change the binding of a function defined with defun
?
推荐答案
因为 Common Lisp 对函数有不同的命名空间,所以需要使用 symbol-function
或 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 中的函数绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!