Last active
April 6, 2020 18:15
-
-
Save justinhj/7c7a1f03902baadbc68930e378fa2591 to your computer and use it in GitHub Desktop.
It's always Traverse!
This file contains 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
import cats._ | |
import cats.implicits._ | |
import cats.data.Const | |
// List version | |
Traverse[List].traverse(List(1,2,3,4,5,6))(a => if(a%2==0) Const.of[Any](List(a)) else Const.of[Any](List.empty[Int]) | |
).getConst | |
res7: List[Int] = List(2, 4, 6) | |
// Generic version | |
def filter2[A, F[_]: Traverse, G[_]: Applicative](fa: F[A])(f: A => Boolean)(implicit app: Applicative[G], m: Monoid[G[A]]): G[A] = { | |
Traverse[F].traverse(fa)(a => if(f(a)) Const.of[Any](app.pure(a)) else Const.of[Any](m.empty)).getConst | |
} | |
filter2[Int, List, LazyList](List(1,2,3,4,5))(a => a > 2) | |
// LazyList[Int] = LazyList(3, 4, 5) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment