在Common Lisp中定义setf-expanders

时间:2012-07-12 17:13:05

标签: common-lisp setf

事情就是这样:我没有“获得”setf-expanders,并希望了解它们是如何工作的。

我需要了解它们是如何工作的,因为我遇到了一个问题,这似乎是为什么你应该学习setf-expanders的一个典型例子,问题如下:

(defparameter some-array (make-array 10))

(defun arr-index (index-string)
  (aref some-array (parse-integer index-string))

(setf (arr-index "2") 7) ;; Error: undefined function (setf arr-index)

如何为ARR-INDEX写一个合适的setf-expander?

2 个答案:

答案 0 :(得分:19)

(defun (setf arr-index) (new-value index-string)
  (setf (aref some-array (parse-integer index-string))
        new-value))

在Common Lisp中,function name不仅可以是符号,还可以是以SETF作为第一个符号的两个符号的列表。往上看。 DEFUN因此可以定义SETF个函数。函数的名称是(setf arr-index)

setf函数可以 place 形式使用:CLHS: Other compound forms as places

新值是第一个参数。

CL-USER 15 > some-array
#(NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL)

CL-USER 16 > (setf (arr-index "2") 7)
7

CL-USER 17 > some-array
#(NIL NIL 7 NIL NIL NIL NIL NIL NIL NIL)

答案 1 :(得分:4)

Rainer的回答很明显。在ANSI Common Lisp之前,有必要使用defsetf为可以通过简单函数调用设置的简单位置定义扩展器。像setf这样的(setf arr-index)函数与CLOS一起使用,并简化了很多事情。特别是,setf函数可以是通用的。