newLISP Fan Club

Forum => newLISP in the real world => Topic started by: Fanda on August 24, 2005, 11:27:52 PM

Title: How to overload and save your old function
Post by: Fanda on August 24, 2005, 11:27:52 PM
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.


;
; 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)


;
; 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 ;-)
Title:
Post by: Fanda on September 18, 2005, 11:38:05 PM
If you wanna repeatedly run your code, you can use this:


;
; 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).
; new randomize
(define (nrandomize x)
  (if (list? x)
    (old-randomize x)
    (if (string? x)
      (join (old-randomize (explode x)))
      x)))


Run:
> (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