且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

函数中的setf不起作用

更新时间:2022-12-18 09:50:58

您需要将变量数据设置为新的新鲜列表,该列表是文字数据的副本.不要让全局变量指向函数的本地文字数据.

您正在查看的也是Common Lisp程序中未定义的行为.

What you are looking at is also undefined behavior in a Common Lisp program.

您在函数中使用文字数据.稍后,您可以通过更改列表的第二个元素来修改此文字数据.确切发生的情况尚未宣布.一些可能的结果:

You use literal data in the function. Later you modify this literal data by changing the second element of the list. What exactly happens is undeclared. Some possible outcomes:

  • 数据与其他一些变量共享,都可以看到更改.
  • 发生错误,因为文字数据可能位于只读存储器中
  • 数据已更改

许多实现只是更改文字数据.在这种情况下,函数的数据将被更改.

Many implementation just change the literal data. Here in this case the data of the function is changed.

如果要让函数重置变量值并创建非文字数据,则需要首先复制文字列表.

If you want the function to reset the variable value and create not-literal data, you need to copy the literal list first.

CL-USER 30 > (defparameter *unsorted-lst* nil)
*UNSORTED-LST*

CL-USER 31 > (defun reset-to-unsorted-list ()
               (setf *unsorted-lst*
                     (copy-list '(1 3  0 22 3 1 3 299 31 5 0 3 7 96 24 44)))
               (format t "after reset: ~a~%" *unsorted-lst*))
RESET-TO-UNSORTED-LIST

CL-USER 32 > (setf *unsorted-lst* '(1 2 3))
(1 2 3)

CL-USER 33 > (reset-to-unsorted-list)
after reset: (1 3 0 22 3 1 3 299 31 5 0 3 7 96 24 44)
NIL

CL-USER 34 > (setf (second *unsorted-lst*) 100)
100

CL-USER 35 > (reset-to-unsorted-list)
after reset: (1 3 0 22 3 1 3 299 31 5 0 3 7 96 24 44)
NIL