2013-03-21 74 views
2

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的时候,但我想明白为什么行为从文档的不同(至少从返回,而不是抛出一个异常的空队列很多我通过阅读文档了解到)。

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

回答

0

你是对的,在文档字符串中似乎确实存在矛盾。目前,弹出一个空队列给出一个空队列。这样看来,核心开发者辩论中​​期望的行为所作的评论来看:

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); 
} 

我不认为自己安全的假设这种行为绝不会在未来被改变。

+0

因此,如果我想采取防御措施,我可以编写一个* safe-pop *函数,它将使用* try */* catch *,并在引发异常时返回nil? – 2013-03-21 02:33:38

+0

我不知道试图捕捉一个还不存在的异常(并且可能永远不会)。我可能更倾向于测试自己的空洞,并且抛出异常或者返回零,因为我认为合适。 – 2013-03-21 03:06:04