這個問題是關於通用Lisp setf
宏,以及它如何評估其參數形式(和子形式) - 即只有一次,如果它們碰巧不止一次出現。 (這也部分跟進在Using get-setf-expansion在評論中給出的例子。)setf形式的評估
;create a list of two hash tables
* (defparameter hts (list (make-hash-table) (make-hash-table)))
HTS
* hts
(#<HASH-TABLE :TEST EQL :COUNT 0 {1007F76CB3}>
#<HASH-TABLE :TEST EQL :COUNT 0 {1007F77103}>)
;define a function that swaps the position of the two hash tables
* (defun next-ht (hts)
(rotatef (first hts) (second hts))
(second hts))
NEXT-HT
交換:
;now do a swap to verify it works
* (next-ht hts)
#<HASH-TABLE :TEST EQL :COUNT 0 {1007F76CB3}>
* hts
(#<HASH-TABLE :TEST EQL :COUNT 0 {1007F77103}>
#<HASH-TABLE :TEST EQL :COUNT 0 {1007F76CB3}>)
;and swap them back
* (next-ht hts)
#<HASH-TABLE :TEST EQL :COUNT 0 {1007F77103}>
* hts
(#<HASH-TABLE :TEST EQL :COUNT 0 {1007F76CB3}>
#<HASH-TABLE :TEST EQL :COUNT 0 {1007F77103}>)
進一步測試:
;then set different values for a key in each table
* (setf (gethash 0 (first hts)) 11)
11
* (setf (gethash 0 (second hts)) 22)
22
* hts
(#<HASH-TABLE :TEST EQL :COUNT 1 {1007F76CB3}>
#<HASH-TABLE :TEST EQL :COUNT 1 {1007F77103}>)
;finally execute a setf with a swapping side-effect
* (setf (gethash 0 (next-ht hts)) (1+ (gethash 0 (next-ht hts))))
23
;but it looks like hts has been swapped twice
;back to its original state
* hts
(#<HASH-TABLE :TEST EQL :COUNT 1 {1007F76CB3}>
#<HASH-TABLE :TEST EQL :COUNT 1 {1007F77103}>)
;also, where did the initial value of 11 go?
* (gethash 0 (first hts))
23
T
* (gethash 0 (second hts))
22
T
*
可有人澄清所發生的事情?另外,帶有副作用的setf
表達式的含義是什麼?
'SETF'不會阻止從子表單被評估兩次。修改像'INCF'這樣的宏。 – jkiiski
@jkiiski這是我正在尋找的區別。我以前的印象是'setf' *是某種修改宏,因爲這個地方只是傳遞給'get-setf-expansion'。謝謝。 – davypough