-
-
Save Tvaroh/f3c69cdf7a7a52b1ea2b6019e20c2646 to your computer and use it in GitHub Desktop.
collectFirstM using 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
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