实验代码:
(setq t1 '((0 . "a") (1 . "b")))
(let ((o1 t1)
(o2 (copy-sequence t1))
(o3 (cl-copy-list t1))
(o4 (copy-alist t1))
(o5 (copy-tree t1)))
;; (setcar (car t1) 4) ;; Test A
(setcdr t1 4) ;; Test B
(message "t1: %S\nlet: %S\ncopy-sequence: %S\ncl-copy-list: %S\ncopy-alist: %S\ncopy-tree: %S" t1 o1 o2 o3 o4 o5))
结果:
;; 初始值; ((0 . "a") (1 . "b"))
;;; Test A 替换cons cell的内部元素
;; t1: ((4 . "a") (1 . "b"))
;; let: ((4 . "a") (1 . "b"))
;; copy-sequence: ((4 . "a") (1 . "b"))
;; cl-copy-list: ((4 . "a") (1 . "b"))
;; copy-alist: ((0 . "a") (1 . "b"))
;; copy-tree: ((0 . "a") (1 . "b"))
;;; Test B 替换list中的一个元素
;; t1: ((0 . "a") . 4)
;; let: ((0 . "a") . 4)
;; copy-sequence: ((0 . "a") (1 . "b"))
;; cl-copy-list: ((0 . "a") (1 . "b"))
;; copy-alist: ((0 . "a") (1 . "b"))
;; copy-tree: ((0 . "a") (1 . "b"))
两次测试,copy-alist
和 copy-tree
都没变,都是深拷贝嘛?
而 copy-sequence
和 cl-copy-list
变化则保持一致,他们之间又有什么区别呢?
大家更常用哪些方法呢?比如我现在想要比较 一个 alist 变量的值有没有发生改变,是用的 copy-tree
。