如何在Common Lisp中设置一个函数

zst*_*art 3 lisp common-lisp

在Common Lisp中,我可以得到一个函数来传递#'语法,如下所示:

(let ((x #'+))
 (funcall x 1 2))
Run Code Online (Sandbox Code Playgroud)

但是假设我想设置一个函数,所以我不必使用funcall它.Common Lisp是否具有本地函数名称表,或仅具有分配给它的全局函数名称表defun?

有没有办法分配给除以外的功能符号defun?或者更一般地说:有没有办法可以做类似于这个非工作的例子:

(setf #'x #'+)
(x 1 2)
Run Code Online (Sandbox Code Playgroud)

sds*_*sds 12

您可以使用flet和labels定义本地函数 :

(flet ((f (x) (1+ (* 2 x))))
  (f 7))
==> 15
Run Code Online (Sandbox Code Playgroud)

您还可以使用fdefinition以下方法设置符号的函数定义:

(setf (fdefinition 'f) #'+)
(f 1 2 3)
==> 6
Run Code Online (Sandbox Code Playgroud)

注意,let绑定功能单元时绑定符号的 值单元格.当符号出现在"功能"位置时,使用"功能"单元格,而当它出现在"值"位置时,使用"值"单元格:flet

(setf (symbol-function 'x) #'car)
(setf (symbol-value 'x) #'cdr)
(x '(1 . 2))
==> 1
(funcall x '(1 . 2))
==> 2
Run Code Online (Sandbox Code Playgroud)

同样的,

(flet ((x (o) (car o)))
  (let ((x #'cdr))
    (cons (x '(1 . 2))
          (funcall x '(1 . 2)))))
==> (1 . 2)
Run Code Online (Sandbox Code Playgroud)

这是Lisp-1和Lisp-2之间的区别.

最后,请注意CLISP只是ANSI Common Lisp语言的一种实现.