Skip to content

Instantly share code, notes, and snippets.

@robinp
Created September 23, 2012 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinp/3769565 to your computer and use it in GitHub Desktop.
Save robinp/3769565 to your computer and use it in GitHub Desktop.
oom-ing recursion
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)
}
}
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")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment