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一个空队列将始终返回一个空队列(这将与文档相矛盾)。
你是正确的,在文档字符串中似乎存在矛盾。目前,弹出一个空队列会产生一个空队列。从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);
}
如果这种行为在将来永远不会改变,我不会认为自己是安全的。