Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

defining setf-expanders in Common Lisp

Here's the thing: I don't "get" setf-expanders and would like to learn how they work.

I need to learn how they work because I've got a problem which seems like a typical example for why you should learn setf-expanders, the problem is as follows:

(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)

How do I write a proper setf-expander for ARR-INDEX?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
(defun (setf arr-index) (new-value index-string)
  (setf (aref some-array (parse-integer index-string))
        new-value))

In Common Lisp a function name can not only be a symbol, but also a list of two symbols with SETF as the first symbol. See above. DEFUN thus can define SETF functions. The name of the function is (setf arr-index).

A setf function can be used in a place form: CLHS: Other compound forms as places.

The new value is the first argument then.

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...