这个问题是关于 Common Lispsetf
宏,以及它如何评估它的参数形式(和子形式)——也就是说,如果它们碰巧出现不止一次,则只有一次。(这也是对Using get-setf-expansion评论中给出的示例的部分跟进。)
;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
带有副作用的表达式是什么意思?