1

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?

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
Y.S
  • 311
  • 1
  • 10

1 Answers1

8

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
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
  • Thank you, i figured i have to somehow write the function to the symbol however I had no clue how to do that. – Y.S Sep 13 '16 at 21:21
  • You can also (setf bar (symbol-function 'foo)) - but then to invoke you would have to go (**funcall** bar 1 2). – Mongus Pong Sep 14 '16 at 11:32