Skip to content

Instantly share code, notes, and snippets.

@Tvaroh
Forked from Odomontois/collectFirst.scala
Last active January 11, 2018 13:26
Show Gist options
  • Save Tvaroh/f3c69cdf7a7a52b1ea2b6019e20c2646 to your computer and use it in GitHub Desktop.
Save Tvaroh/f3c69cdf7a7a52b1ea2b6019e20c2646 to your computer and use it in GitHub Desktop.
collectFirstM using cats
import cats.implicits._
object CollectFirstM {
implicit class CollectFirstMSyntax[F[_], A](val xs: Seq[A]) extends AnyVal {
def collectFirstM[B, M[_]](f: A => M[Option[B]])(implicit M: Monad[M]): M[Option[B]] =
M.tailRecM(xs) {
case x +: rest => f(x).map {
case some@Some(_) => Right(some)
case None => Left(rest)
}
case _ => Either.right[Seq[A], Option[B]](None).pure[M]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment