Search code examples
schemelispcommon-lispfirst-class-functions

How do I copy a function to a new symbol?


I've got a question regarding the copy of function in Common Lisp.

In Scheme I'd go with:

(define (foo par1 par2) (+ par1 par2))
(define bar foo)
(print (bar 1 2)) ;; --> prints 3
(define (foo par1 par2) (* par1 par2))
(print (bar 1 2)) ;; --> prints again 3
(print (foo 1 2)) ;; --> prints 2

How can i do this with Common Lisp?


Solution

  • One of the differences between Scheme and Common Lisp is, that Common Lisp has separate namespaces for functions and values. In Scheme we can set the value - that's also all that is there. In Common Lisp we need to set the function and not the value, if we want to set or change the function of a symbol.

    SYMBOL-FUNCTION gives you the function for a symbol. You can use the function (setf symbol-function) to set the function of a symbol. See below for an example:

    CL-USER 50 > (defun foo (par1 par2) (+ par1 par2))
    FOO
    
    CL-USER 51 > (setf (symbol-function 'bar) (symbol-function 'foo))
    #<interpreted function FOO 4060000C3C>
    
    CL-USER 52 > (bar 1 2)
    3
    
    CL-USER 53 > (defun foo (par1 par2) (* par1 par2))
    FOO
    
    CL-USER 54 > (bar 1 2)
    3
    
    CL-USER 55 > (foo 1 2)
    2