Created
May 9, 2016 00:07
-
-
Save non/af98eff7c6fff67f866a066b20343f4c to your computer and use it in GitHub Desktop.
Demo using Cats/Dogs to implement lazy memoization, similar to this Haskell gist: https://gist.github.com/beala/d871ae8397167e7035f218a25ddf87dd
This file contains hidden or 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
package beala | |
import dogs._ | |
object Beala { | |
// ironically dogs doesn't support unsafe operations by default, | |
// so we have to build them ourselves (since we know our stream | |
// is infinite and will always have elements). | |
def head[A](as: Streaming[A]): A = | |
as.uncons.getOrElse(sys.error("empty head"))._1 | |
def get[A](as: Streaming[A], i: Int): A = | |
head(as.drop(i)) | |
lazy val fibs: Streaming[Long] = | |
Streaming.from(0).map { | |
case 0 => 0L | |
case 1 => 1L | |
case n => get(fibs, n - 1) + get(fibs, n - 2) | |
}.memoize | |
def slow(i: Int): Long = | |
if (i == 0) 0L | |
else if (i == 1) 1L | |
else slow(i - 1) + slow(i - 2) | |
def fast(i: Int): Long = | |
get(fibs, i) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment