Created
March 16, 2019 04:38
-
-
Save afsalthaj/976fe7684004ebfe3c6101288dce1226 to your computer and use it in GitHub Desktop.
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 scala.util.Random | |
sealed trait Streamss[A, B] | |
object Streamss extends App { | |
case class NeedInput[A, B](f: A => Streamss[A, B]) extends Streamss[A, B] | |
case class HasOutput[A, B](b: B, s: Streamss[A, B]) extends Streamss[A, B] | |
case class Done[A, B]() extends Streamss[A, B] | |
// run length encoding using streams (http://haskell-for-readers.nomeata.de/#algebraic-data-types) | |
def streams[A]: Streamss[A, (Int, A)] = NeedInput(rlestart[A]) | |
def rlestart[A]: A => Streamss[A, (Int, A)] = a => NeedInput(relCount(a, 1)) | |
def relCount[A](a: A, i: Int): A => Streamss[A, (Int, A)] = | |
newA => | |
if (newA == a) NeedInput(relCount(a, i + 1)) else HasOutput((i, a), rlestart(newA)) | |
def run(s: Streamss[Int, (Int, Int)]): Unit = | |
s match { | |
case NeedInput(f) => run(f({ | |
Random.nextInt(2) | |
})) | |
case HasOutput(b, ss) => { | |
println(b); run(ss) | |
} | |
} | |
run(streams[Int]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment