Created
September 23, 2012 10:04
-
-
Save robinp/3769565 to your computer and use it in GitHub Desktop.
oom-ing recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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