Mat*_*att 2 lisp variables scheme binding common-lisp
以下是您可以在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
Run Code Online (Sandbox Code Playgroud)
如果我在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
Run Code Online (Sandbox Code Playgroud)
现在我该如何做这样的事情(setf sum #'sum-debug)会改变定义的函数的绑定defun?
因为Common Lisp具有不同的函数名称空间,所以您需要使用symbol-function或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>
Run Code Online (Sandbox Code Playgroud)
以这种方式重新定义功能的典型用例是在调试期间.你的例子表明了.Common Lisp已经为此提供了更高级别的机制:TRACE.它设置了符号的功能值,但它提供了更方便的用户界面.通常类似的东西TRACE会有很多非标准的选择.
跟踪功能
以下示例使用Clozure Common Lisp,它总是编译代码:
? (defun sum (list accumulator)
(declare (optimize debug)) ; note the debug declaration
(if (endp list)
accumulator
(sum (rest list) (+ accumulator (first list)))))
SUM
? (sum '(1 2 3 4) 0)
10
? (trace sum)
NIL
? (sum '(1 2 3 4) 0)
0> Calling (SUM (1 2 3 4) 0)
1> Calling (SUM (2 3 4) 1)
2> Calling (SUM (3 4) 3)
3> Calling (SUM (4) 6)
4> Calling (SUM NIL 10)
<4 SUM returned 10
<3 SUM returned 10
<2 SUM returned 10
<1 SUM returned 10
<0 SUM returned 10
10
Run Code Online (Sandbox Code Playgroud)
然后去解雇:
? (untrace sum)
Run Code Online (Sandbox Code Playgroud)
建议功能
在您的示例中,您已经打印了有关输入函数的参数.在许多Common Lisp实现中,还有另一种机制可以通过增加功能来增强功能:建议.再次使用Clozure Common Lisp及其advise宏:
? (advise sum ; the name of the function
(format t "~%Arglist: ~a" arglist) ; the code
:when :before) ; where to add the code
#<Compiled-function (CCL::ADVISED 'SUM) (Non-Global) #x302000D7AC6F>
? (sum '(1 2 3 4) 0)
Arglist: ((1 2 3 4) 0)
Arglist: ((2 3 4) 1)
Arglist: ((3 4) 3)
Arglist: ((4) 6)
Arglist: (NIL 10)
10
Run Code Online (Sandbox Code Playgroud)