Skip to content

Instantly share code, notes, and snippets.

@markhibberd
Created June 5, 2011 15:45
Show Gist options
  • Save markhibberd/1009072 to your computer and use it in GitHub Desktop.
Save markhibberd/1009072 to your computer and use it in GitHub Desktop.
Alt D List Example
package scalaz.example
import scalaz.AltDList._
object ExampleAltDList {
def main(args: Array[String]) = run
import scalaz._, Scalaz._
import IterV._
// something to generate a stream that will be enough to blow the stack....
def ints[A]: (Int, Int) => IterV[Int, A] => IterV[Int, A] = (start, end) => iter => {
def loop(s: Int, i: IterV[Int, A]): IterV[Int, A] = i match {
case Done(_, _) => i
case Cont(k) =>
if (s > end)
i
else
loop(s + 1, k(El(s)))
}
loop(start, iter)
}
// used to check ::> does not blow the stack
def toAltDList[A]: IterV[A, AltDList[A]] = {
def step(acc: AltDList[A])(s: Input[A]): IterV[A, AltDList[A]] =
s(el = e => Cont(step(acc ::> e)),
empty = Cont(step(acc)),
eof = Done(acc, EOF.apply))
Cont(step(AltDList.empty))
}
implicit def AltDListSemiGroup[A]: Semigroup[AltDList[A]] = semigroup(_ ::: _)
implicit def AltDListZero[A]: Zero[AltDList[A]] = zero(AltDList.empty)
// used to check ':::' does not blow the stack
def AltDListSemigroupReducer[C] = new Reducer[C, AltDList[C]] {
override def unit(c: C) = c :: AltDList.empty[C]
override def cons(c: C, cs: AltDList[C]) = (c :: AltDList.empty) ::: cs
}
// used to check '::' does not blow the stack
def AltDListConsReducer[C] = new Reducer[C, AltDList[C]] {
override def unit(c: C) = c :: AltDList.empty[C]
override def cons(c: C, cs: AltDList[C]) = c :: cs
}
def run {
val expected = (0 to 20000).toList
ints(0, 20000)(toAltDList).run.toList assert_=== expected // check '::>' does not blow the stack
ints(0, 20000)(reversed(AltDListConsReducer)).run.toList.reverse assert_=== expected // check '::' does not blow the stack
ints(0, 20000)(reversed(AltDListSemigroupReducer)).run.toList.reverse assert_=== expected // check ':::' does not blow the stack
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment