feat: replace eager list-based map/where with deferred MapSequence and WhereSequence classes

Introduce MapSequence and WhereSequence subclasses of Sequence that apply transformations lazily during iteration instead of building intermediate lists. Update Sequence.map and Sequence.where to return these deferred wrappers, modify all existing tests to call .list on results, and add new infinite-sequence tests verifying lazy behavior on Fibonacci iterators.
This commit is contained in:
Thorbjørn Lindeijer
2015-03-28 21:51:50 +00:00
parent adc64d65b9
commit 5b71ac0c56
9 changed files with 160 additions and 44 deletions
+28 -14
View File
@@ -26,21 +26,9 @@ class Sequence {
return result
}
map(f) {
var result = new List
for (element in this) {
result.add(f.call(element))
}
return result
}
map(transformation) { new MapSequence(this, transformation) }
where(f) {
var result = new List
for (element in this) {
if (f.call(element)) result.add(element)
}
return result
}
where(predicate) { new WhereSequence(this, predicate) }
all(f) {
for (element in this) {
@@ -100,6 +88,32 @@ class Sequence {
}
}
class MapSequence is Sequence {
new(seq, f) {
_seq = seq
_f = f
}
iterate(n) { _seq.iterate(n) }
iteratorValue(iterator) { _f.call(_seq.iteratorValue(iterator)) }
}
class WhereSequence is Sequence {
new(seq, f) {
_seq = seq
_f = f
}
iterate(n) {
while (n = _seq.iterate(n)) {
if (_f.call(_seq.iteratorValue(n))) break
}
return n
}
iteratorValue(iterator) { _seq.iteratorValue(iterator) }
}
class String is Sequence {
bytes { new StringByteSequence(this) }
}