redefining built-in function

前端 未结 1 1517
闹比i
闹比i 2021-01-05 19:51

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 \'commo         


        
相关标签:
1条回答
  • 2021-01-05 20:09

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

    0 讨论(0)
提交回复
热议问题