filter on lazy seq causes stack overflow
Description
Environment
Tested in firefox 21.0 and chromium 27.0.1453.93
Activity
David Nolen September 26, 2013 at 9:36 PM

Lars Bohl September 15, 2013 at 10:01 AM
Using a javascript debugger (chromium built-in) on the (first (filter #(= 9999 %) (range))) call, I found out that this is the concrete implementation of "first" that gets called:
cljs.core.LazySeq.prototype.cljs$core$ISeq$_first$arity$1 = function(coll) {
var self__ = this;
return cljs.core.first.call(null, cljs.core.lazy_seq_value.call(null, coll))
};
where this is lazy_seq_value:
cljs.core.lazy_seq_value = function lazy_seq_value(lazy_seq) {
var x = lazy_seq.x;
if(lazy_seq.realized) {
return x
}else {
lazy_seq.x = x.call(null);
lazy_seq.realized = true;
return lazy_seq.x
}
};
Compare this with clojure's java implemetation of "first" that gets called by the same code (https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/LazySeq.java):
public Object first(){
seq();
if(s == null)
return null;
return s.first();
}
where seq is this defined like this:
final synchronized public ISeq seq(){
sval();
if(sv != null)
{
Object ls = sv;
sv = null;
while(ls instanceof LazySeq)
{
ls = ((LazySeq)ls).sval();
}
s = RT.seq(ls);
}
return s;
}
The while loop in LazySeq#seq seems to avoid the stack problems in clojure. Whereas clojurescript, there is no while loop in LazySeq's implementation of first. Maybe the problem will disappear if it is added there in some way?

Lars Bohl September 10, 2013 at 7:06 AM
Affect clojurescipt version 0.0-1859
Details
Details
Assignee
Reporter

Priority

This expression causes a stack overflow, instead evaluating to 9999:
(first (filter #(= 9999 %) (range)))
These expressions should be equivalent, and do not cause a stack overflow:
(first (filter #(= 9999 %) (vec (take 10000 (range)))))
(some #(when (= 9999 %) %) (range))
Thus, it seems as if filter cannot handle an input that's already lazy.
More elaborate version: https://www.refheap.com/18490
See also this google group thread: https://groups.google.com/forum/#!topic/clojurescript/3NlQOxwNrRc
Please consider using ssl on dev.clojure.org ##