gstar2002
gstar2002

Reputation: 21

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

rt. I want to redefine a function at run time so that i can change the behavior of the system at run time. thanks.

Upvotes: 2

Views: 1696

Answers (3)

Zorf
Zorf

Reputation: 6464

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.

Upvotes: 1

JeSuisse
JeSuisse

Reputation: 359

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)

Upvotes: 0

Eli Barzilay
Eli Barzilay

Reputation: 29556

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

Upvotes: 5

Related Questions