gpt4 book ai didi

common-lisp - 同时为多个地方分配相同的值?

转载 作者:行者123 更新时间:2023-12-04 23:54:35 24 4
gpt4 key购买 nike

我想为两个(或更多)变量分配相同的值,例如 xy(z 等)从用户输入中读取。现在我有了 (setf x (read)),但我还想将输入值也放入 y 中。然后我必须执行 (setf y x) 吗?有没有更优雅的东西?

(setf x (read) y (read))

只让用户输入两次,所以这不好。

最佳答案

虽然您可以轻松地实现它,但语言中并没有什么比这更像的了。例如,这里有一个宏 setf*(虽然不是最好的名字),它将一个值分配给一堆地方(不一定是变量):

(defmacro setf* ((&rest places) value)
(let ((temp (gensym)))
`(let ((,temp ,value))
(setf ,@(mapcan (lambda (place)
(list place temp))
places)))))

CL-USER> (macroexpand-1 '(setf* (a (car list) (aref array 2 3)) d))
(LET ((#:G1043 D))
(SETF A #:G1043
(CAR LIST) #:G1043
(AREF ARRAY 2 3) #:G1043))

你会做

(setf* (x y) (read))

当然,对于简单的关闭,您也可以手动执行此操作(如 sds 所建议的):

(setf x (read)
y x)

(let ((temp (read)))
(setf x temp
y temp))

关于common-lisp - 同时为多个地方分配相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33440477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com