Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

variables - How can I modify function bindings in 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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...