Skip to content

Instantly share code, notes, and snippets.

@YuvalItzchakov
Created April 15, 2017 16:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YuvalItzchakov/88e267fd44719f0a8e82bf807843a816 to your computer and use it in GitHub Desktop.
Save YuvalItzchakov/88e267fd44719f0a8e82bf807843a816 to your computer and use it in GitHub Desktop.
Lazy dropWhile with Cats
package tests
import cats._
import cats.implicits._
import scala.collection.immutable.Stream
/**
* Created by Yuval.Itzchakov on 3/8/2017.
*/
object Test {
def dropWhile[F[_]: Foldable : Applicative : MonoidK, A]
(fa: F[A], pred: (A) => Boolean): Eval[F[A]] = {
def combine(x: A, xs: Eval[F[A]]): Eval[F[A]] = {
if (pred(x))
xs
else
xs.map(s => MonoidK[F].algebra.combine(Applicative[F].pure(x), s))
}
val base: F[A] = MonoidK[F].empty[A]
Foldable[F].foldRight(fa, Later(base))(combine)
}
def main(args: Array[String]): Unit = {
val stream = Stream(1,2,3,4,5)
val list = List(1,2,3,4,5)
val resStream = dropWhile(stream, (i: Int) => i <= 3)
val resList = dropWhile(list, (i: Int) => i <= 3)
println("------- Stream ----------")
resStream.value.foreach(println)
println("------- List ---------")
resList.value.foreach(println)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment