Reputation: 6014
The doc for the pop
function says that:
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.
However I can't seem to reproduce the behavior where an exception should be thrown.
For example here I add three elements to the queue then pop
five times: according to the doc this shouldn't work. However, instead of having an exception, I get nil.
(peek (pop (pop (pop (pop (pop (conj (conj (conj clojure.lang.PersistentQueue/EMPTY 4) 5) 6)))))))
Now I like a lot that instead an empty queue is returned instead of throwing an exception when trying to pop
from the empty queue but I'd like to understand why the behavior differs from the doc (at least from what I understand from reading the docs).
Basically I'd like to know if I should "protect" myself from an exception here or if I can safely assume that pop
'ing an empty queue shall always return an empty queue (which would contradict the doc).
Upvotes: 3
Views: 289
Reputation: 26446
You are correct, there does appear to be a contradiction in the doc string. Currently, popping an empty queue gives an empty queue. It would appear the core developers were debating the desired behavior judging by the comments in 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);
}
I wouldn't consider myself safe assuming this behavior will never be changed in the future.
Upvotes: 1