public
Created

oom-ing recursion

  • Download Gist
ok.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
import java.util.concurrent.atomic.AtomicReference
 
object ok {
 
@scala.annotation.tailrec
final def filter[A](s: Stream[A], f: A => Boolean): Stream[A] =
s match {
case hd #:: tl =>
val tailRef = new AtomicReference(tl)
if (f(hd)) hd #:: filterHelp(tailRef, f)
else filter(tl, f)
 
case _ => Stream.empty
}
 
final def filterHelp[A](sr: AtomicReference[Stream[A]], f: A => Boolean) =
filter(sr.getAndSet(null), f)
 
val big = 100 * 1000 * 1000
 
def s1 = Stream.range(1, big)
 
def main(args: Array[String]) {
println("start")
var cnt = 0
filter(s1, (x: Int) => x == 1) foreach { _ => cnt += 1 }
println(cnt)
}
 
}
oom.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
object oom extends App {
 
@scala.annotation.tailrec
def filter[A](s: Stream[A], f: A => Boolean): Stream[A] =
s match {
case hd #:: tl =>
if (f(hd)) hd #:: filterHelp(tl, f)
else filter(tl, f)
 
case _ => Stream.empty
}
 
def filterHelp[A](s: Stream[A], f: A => Boolean) =
filter(s, f)
 
val big = 10000000
 
def s1 = Stream.range(1, big)
 
println("start")
val streamSum = filter(s1, (x: Int) => x == 1).sum
println("stop")
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.