redefining built-in function
Asked Answered
T

1

7

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

Transcontinental answered 28/3, 2013 at 20:49 Comment(0)
D
13

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".

Dyane answered 28/3, 2013 at 21:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.