Weak as in weak references. Basically, I need a sequence of numbers where some of them can be unallocated when they aren't needed anymore.
Asked
Active
Viewed 218 times
6
-
4You should be glad you don't have a weak stream (sorry, couldn't resist) – Tom Crockett Mar 27 '11 at 18:45
-
http://stackoverflow.com/questions/4132924/functional-processing-of-scala-streams-without-outofmemory-errors – 0__ Mar 27 '11 at 20:09
-
@Sciss Sorry, couldn't find anything when I searched... well, that happens sometimes, right? – Anonymous Mar 27 '11 at 21:31
3 Answers
0
Views provide you with a lazy collection, where each value is computed as it is needed.
Bradford
- 4,143
- 2
- 34
- 44
-
Yes. I already have a lazy collection (Stream), but I need it to be weak too. – Anonymous Mar 27 '11 at 21:22
-
The whole point of the question... gotcha! Thanks. I'll leave my answer here for others to see these comments. Can someone perhaps explain why Views are not weak? – Bradford Mar 27 '11 at 21:33
-
2The distinction is that views do not cache computed elements at all, while a weak stream will cache its elements until they are garbage collected. – Aaron Novstrup Mar 28 '11 at 03:37
0
One thing you could do is create an Iterable instead of a Stream. Your Iterable needs to provide an iterator method, which returns an iterator with hasNext and next methods.
When you loop over the Iterable, hasNext and next will be called to generate the elements as they are needed, but they are not stored anywhere (like a Stream does).
Simple example:
class Numbers extends Iterable[Int] {
def iterator = new Iterator[Int] {
private var num = -1
def hasNext = num < 99
def next = { num += 1; num }
}
}
Jesper
- 202,709
- 46
- 318
- 350
-
That wouldn't help much, because I need a stream for two reasons: functional programming (= not iterators) and memoization (not iterables). – Anonymous Mar 28 '11 at 22:50
-
@Anonymous - note that `Iterable` has most Scala collection methods (including `foreach`, `map`, `filter`, `foldLeft` etc) so you can use it for func programming just like any other collection, and memoization: I thought you wanted something that does *not* retain the generated values? – Jesper Mar 29 '11 at 11:03
-
It should retain them, just not permanent. Look at (I think) java.lang.ref.WeakReference. – Anonymous Mar 29 '11 at 12:29