开发者

How can i overload a function at run time in Scheme?

rt. I want to redefine a functio开发者_Go百科n at run time so that i can change the behavior of the system at run time. thanks.


(define (foo x) ...stuff...)
(set! foo (lambda (x) ...different stuff...))


It might be advisable to use let to do this locally, this can also apply to keywords in this sense:

(let ((define +))
   (define 2 3)) ; ===> 5

Or even redefine them to constants, remember, Scheme is a lisp-1:

(let ((define 2) (+ 4))
   (- define +)) ; ===> -2

Or even:

(let ((quote /))
   '3) ===> 1/3

Doing it only locally preserves the functional style.


Assuming you want to overload a function you defined earlier, simply define it again. This also works for redefining functions such as car and cdr, e.g. to make car into cdr:

(define (car x) (cdr x))

However, I think you won't be able to affect other already defined functions with such a redefinition, so a system function which uses car will still use the original system car and not yours:

(define (test x) (car x))

(define (car x) (cdr x))

(test '(1 2 3))

1

I guess the reason for this is that internally the symbols disappear once a function gets read or evaluated and the symbols are replaced by what they're bound to; in this case, the actual code of the function. So rebinding a symbol to a different function won't affect the rest of your already defined code. This is usually a good thing because it helps uphold referential transparency.

If you want to redefine scheme keywords such as lambda or cond, use let-syntax (see http://community.schemewiki.org/?scheme-faq-language)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜