Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redefining built-in function

How would i redefine a built-in function, while keeping a reference to the old function under a different name?

ie with SBCL

(unlock-package 'common-lisp)
(defun old+ (a b) ??????
(defun + (a b) (old+ a b))

I'm porting code to a LISP implementation that doesn't have float data type. So I wanted to redefine the the math ops to use fixed integer math.

I suppose i can solve this problem with search-and-replace as well :)

like image 362
KingWeeWee Avatar asked Mar 28 '13 20:03

KingWeeWee


1 Answers

To answer your specific question:

(defconstant +old-plus+ (fdefinition '+))
(defun + (&rest args) (apply +old-plus+ args))

Note that if you evaluate this again (e.g., by reloading the file where this code contained), you might have a problem: +old-plus+ might get silently redefined to your new + (or you might get an error, or you might get a warning) and you will lose the original + definition.

Therefore it seems that a better approach would be to create a new package where all symbols are imported from CL except for + which is shadowed, and then use that package instead of CL (untested):

(rename-package "COMMON-LISP" "COMMON-LISP-ORIGINAL")
(make-package "COMMON-LISP")
(use-package "COMMON-LISP-ORIGINAL" "COMMON-LISP")
(shadow "+" "COMMON-LISP")
(do-external-symbols (s "COMMON-LISP-ORIGINAL")
  (export (find-symbol (symbol-name s)) "COMMON-LISP"))
(defun common-lisp::+ (&rest args) (apply #'common-lisp-original:+ args))

Now you should be able to process the code.

Note that you should not load the above code twice because "consequences are undefined" if you rename-package to an existing "COMMON-LISP-ORIGINAL".

like image 81
sds Avatar answered Oct 17 '22 21:10

sds