gpt4 book ai didi

collections - pop 是否抛出异常?

转载 作者:行者123 更新时间:2023-12-04 18:10:14 27 4
gpt4 key购买 nike

pop 函数的文档说:

user> (doc pop)
-------------------------
clojure.core/pop
([coll])
For a list or queue, returns a new list/queue without the first
item, for a vector, returns a new vector without the last item. If
the collection is empty, throws an exception.

但是我似乎无法重现应该抛出异常的行为。

例如,我将三个元素添加到队列中,然后 pop 五次:根据文档,这不应该起作用。但是,我没有得到异常,而是得到了 nil。

(peek (pop (pop (pop (pop (pop (conj (conj (conj clojure.lang.PersistentQueue/EMPTY 4) 5) 6)))))))

现在我非常喜欢在尝试从空队列中 pop 时返回一个空队列而不是抛出异常,但我想了解为什么行为与文档不同(至少从我阅读文档的理解来看是这样。

基本上我想知道我是否应该在这里“保护”自己免受异常的影响,或者我是否可以安全地假设 pop'ing 一个空队列将始终返回一个空队列(这将与文档相矛盾)。

最佳答案

您是对的,文档字符串中确实存在矛盾。目前,弹出一个空队列会得到一个空队列。根据 the source of PersistentQueue 中的评论判断,核心开发人员似乎正在讨论所需的行为。 :

public PersistentQueue pop(){
if(f == null) //hmmm... pop of empty queue -> empty queue?
return this;
//throw new IllegalStateException("popping empty queue");
ISeq f1 = f.next();
PersistentVector r1 = r;
if(f1 == null)
{
f1 = RT.seq(r);
r1 = null;
}
return new PersistentQueue(meta(), cnt - 1, f1, r1);
}

假设这种行为将来永远不会改变,我不会认为自己是安全的。

关于collections - pop 是否抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15537505/

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