Skip to content

Instantly share code, notes, and snippets.

@justinhj
Last active April 6, 2020 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinhj/7c7a1f03902baadbc68930e378fa2591 to your computer and use it in GitHub Desktop.
Save justinhj/7c7a1f03902baadbc68930e378fa2591 to your computer and use it in GitHub Desktop.
It's always Traverse!
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