Skip to content

Instantly share code, notes, and snippets.

@halcat0x15a
Created November 28, 2011 09:14
Show Gist options
  • Save halcat0x15a/1399722 to your computer and use it in GitHub Desktop.
Save halcat0x15a/1399722 to your computer and use it in GitHub Desktop.
戦いの跡。IteratorEnumeratorなんて馬鹿なものは作らないようにしましょう。
import scalaz._
import Scalaz._
import IterV._
object DropWhile {
implicit val IteratorEnumerator = new Enumerator[Iterator] {
def apply[E, A](e: Iterator[E], i: IterV[E, A]): IterV[E, A] = e match {
case iter if iter.hasNext => i.fold(done = (_, _) => i, cont = k => apply(iter, k(El(iter.next))))
case iter => i
}
}
implicit val ListEnumerator = new Enumerator[List] {
def apply[E, A](e: List[E], i: IterV[E, A]): IterV[E, A] = e match {
case Nil => i
case x :: xs => i.fold(done = (_, _) => i, cont = k => apply(xs, k(El(x))))
}
}
implicit val IteratorPure = new Pure[Iterator] {
def pure[A](a: => A) = Iterator(a)
}
implicit def IteratorMonoid[A] = new Monoid[Iterator[A]] {
val zero = Iterator.empty
def append(s1: Iterator[A], s2: => Iterator[A]) = s1 ++ s2
}
implicit def Equal[A] = new Equal[Iterator[A]] {
def equal(a1: Iterator[A], a2: Iterator[A]) = a1 == a2
}
implicit def Show[A] = new Show[Iterator[A]] {
def show(a: Iterator[A]) = a.toString.show
}
def dropWhile[A, F[_]](pred: A => Boolean)(implicit mon: Monoid[F[A]], pr: Pure[F]): IterV[A, F[A]] = peek[A] >>= (_.fold(pred(_).fold(drop(1) >|> dropWhile(pred), collect[A, F]), collect[A, F]))
def main(args: Array[String]) = {
val list = List(1, 1, 2, 3)
val iter = Iterator(1, 1, 2, 3)
val pred: Int => Boolean = _ < 2
val dropWhileIterator = dropWhile[Int, Iterator](pred)
val dropWhileList = dropWhile[Int, List](pred)
dropWhileList(iter).run assert_=== List(2, 3)
dropWhileIterator(iter).run assert_=== Iterator(2, 3)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment