Skip to content

Instantly share code, notes, and snippets.

@afsalthaj
Created March 16, 2019 04:38
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 afsalthaj/976fe7684004ebfe3c6101288dce1226 to your computer and use it in GitHub Desktop.
Save afsalthaj/976fe7684004ebfe3c6101288dce1226 to your computer and use it in GitHub Desktop.
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