3

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五次:根据文档,这不应该工作。但是,我没有例外,而是零。

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

现在我很喜欢在尝试从空队列中返回一个空队列而不是抛出异常pop但我想了解为什么行为与文档不同(至少从我阅读文档中了解到的) .

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

4

1 回答 1

1

您是对的,文档字符串中确实存在矛盾。目前,弹出一个空队列会给出一个空队列。从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);
}

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

于 2013-03-21T01:35:17.173 回答