Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Foldable extension collectFirstSomeM #2366

Merged
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions core/src/main/scala/cats/syntax/foldable.scala
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package cats
package syntax

import cats.data.OptionT

trait FoldableSyntax extends Foldable.ToFoldableOps with UnorderedFoldable.ToUnorderedFoldableOps {
implicit final def catsSyntaxNestedFoldable[F[_]: Foldable, G[_], A](fga: F[G[A]]): NestedFoldableOps[F, G, A] =
new NestedFoldableOps[F, G, A](fga)
Expand Down Expand Up @@ -116,7 +114,10 @@ final class FoldableOps[F[_], A](val fa: F[A]) extends AnyVal {
* }}}
*/
def collectFirstSomeM[G[_], B](f: A => G[Option[B]])(implicit F: Foldable[F], G: Monad[G]): G[Option[B]] =
F.foldRight(fa, Eval.now(OptionT.none[G, B]))((a, lb) =>
Eval.now(OptionT(f(a)).orElse(lb.value))
).value.value
F.foldRight(fa, Eval.now(G.pure(Option.empty[B])))((a, lb) =>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Eval.now(G.flatMap(f(a)) {
case s @ Some(_) => G.pure(s)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could also match on None first and then add case s - we'll avoid an instance check and cast, so it could be good for performance. Not sure if the difference is significant though, we'd need to benchmark. Feel free to ignore this comment ;)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it. Let me perform some jmh benchmarks.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kubukoz JMH proved you right :)

case None => lb.value
})
).value
}