How to overload and save your old function

Q&A's, tips, howto's
Locked
Fanda
Posts: 253
Joined: Tue Aug 02, 2005 6:40 am
Contact:

How to overload and save your old function

Post by Fanda »

Hello!
I have been thinking about it for some time and there seems to be the way how to overload and also save your old function when the new newLISP comes in.

Code: Select all

;
; Overload the old function
;
(constant 'old-add add)

(define (new-add x y)
  (old-add x y 100))

(constant 'add new-add)
Now you can try:
> (add 5 2)
107
> (old-add 5 2)
7

(if you run the code above twice and try (add 5 2), you get the call stack overflow - functions run in the endless recursion)

Code: Select all

;
; Save my old function when the new version of newLISP comes in
;

; my old function
(define (shuffle x)
  (- x))

; when the new version comes in, rename it to my-shuffle
(define (my-shuffle x)
  (- x))

; save the new newLISP function and reassign shuffle to my-shuffle
(constant 'new-shuffle shuffle)
(constant 'shuffle my-shuffle)

; my old code should still work and the new shuffle is as 'new-shuffle'
(println (shuffle 1))
(println (shuffle -5))
(if you run the code above twice, you get collision between (constant 'shuffle) and (define (shuffle)) - nothing special ;-)

Hope you like it, Fanda

ps: As Lutz pointed out, you can also use (constant (global '+) add) to make it global ;-)

Fanda
Posts: 253
Joined: Tue Aug 02, 2005 6:40 am
Contact:

Post by Fanda »

If you wanna repeatedly run your code, you can use this:

Code: Select all

;
; Redefine function
;
(define (redefine old-fn new-fn pre post)
  (if (not (lambda? (eval old-fn)))
    (begin
      (constant (sym (append (or pre "old-") (string old-fn) (or post ""))) (eval old-fn))
      (constant old-fn new-fn))))
=> allows to redefine the function only once
(pre, post is the prefix and the postfix of the symbol we save the old function to)


Little test with 'randomize'. New function has to be defined using old function and pre/post fix (old-randomize).

Code: Select all

; new randomize
(define (nrandomize x)
  (if (list? x)
    (old-randomize x)
    (if (string? x)
      (join (old-randomize (explode x)))
      x)))
Run:

Code: Select all

> (redefine 'randomize nrandomize)
(lambda (x)
 (if (list? x)
  (old-randomize x)
  (if (string? x)
   (join (old-randomize (explode x))) x)))
> (randomize '(1 2 3))
(3 1 2)
> (randomize "newLISP")
"ISwLePn"
> old-randomize
randomize <40F7E0>
You cannot redefine it anymore - safe for running multiple times.
> (redefine 'randomize rand)
nil
> (redefine 'randomize add)
nil

If you wanna go back to your old function, you can run:
> (constant 'randomize old-randomize)
randomize <40F7E0>

(And maybe redefine it again later...)

Fanda

Locked