删除具有破坏性-但并非总是如此吗? [英] DELETE is destructive -- but not always?

查看:81
本文介绍了删除具有破坏性-但并非总是如此吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Common Lisp的破坏性DELETE功能有些困惑。它似乎按预期方式工作,除了该项目是否为列表中的第一项:

  CL-USER> (defvar * test *(列表1 2 3))
* TEST *
CL-USER> (删除1 *测试*)
(2 3)
CL-USER> *测试*
(1 2 3)
CL-USER> (删除2 *测试*)
(1 3)
CL-USER> * test *
(1 3)


解决方案

破坏性并不意味着就地操作。这意味着可以以任意的且通常是未定义的方式修改操作的值的结构。在某些情况下,实现和情况可能像就地起作用。



如果使用破坏性运算符,则告诉编译器您对变量后的先前值不感兴趣。



操作完成。您应该假定该值以后会乱码而无法识别,并且不再使用它。相反,应该使用该操作的返回值。

 (let((a(list 1 2 3)))
(let((b(删除2 a))))
(frob b))
a)

=>你被一个污垢吞噬了。

如果不确定破坏性操作的安全性,请使用其非破坏性对应物(在此情况下删除)。

 (让((a(列出1 2 3 )))
(让((b(删除2 a)))
(frob b))
a)

=> (1 2 3)

如果您确实要修改变量的内容,请将其设置为操作的返回值:

 (let((a(list 1 2 3)))
(setf a (删除2 a))
a)

=> (1 3)


I'm a little confused about Common Lisp's destructive DELETE function. It seems to work as expected, except for if the item is the first item on the list:

CL-USER> (defvar *test* (list 1 2 3))
*TEST*
CL-USER> (delete 1 *test*)
(2 3)
CL-USER> *test*
(1 2 3)
CL-USER> (delete 2 *test*)
(1 3)
CL-USER> *test*
(1 3)

解决方案

"Destructive" does not mean "operates in place". It means that the structure of the value operated on might be modified in some arbitrary and often undefined way. This can in some instances, implementations and cases have an effect as if it was "in place". This can generally not be relied upon, however.

If you use a destructive operator, you are telling the compiler that you are not interested in the previous value of the variable after the operation is complete. You should assume that that value is garbled beyond recognition afterwards and not use it anymore. Instead, you should use the return value of the operation.

(let ((a (list 1 2 3)))
  (let ((b (delete 2 a)))
    (frob b))
  a)

=> You were eaten by a grue.

If you are unsure of the safety of destructive operations, use their non-destructive counterparts (remove in this case).

(let ((a (list 1 2 3)))
  (let ((b (remove 2 a)))
    (frob b))
  a)

=> (1 2 3)

If you really want to modify the contents of a variable, set them to the return value of the operation:

(let ((a (list 1 2 3)))
  (setf a (delete 2 a))
  a)

=> (1 3)

这篇关于删除具有破坏性-但并非总是如此吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆