Created
April 15, 2017 16:12
-
-
Save YuvalItzchakov/88e267fd44719f0a8e82bf807843a816 to your computer and use it in GitHub Desktop.
Lazy dropWhile with Cats
This file contains hidden or 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
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