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

Backport #3130 Add foldMapA to foldable #3351

Merged
merged 3 commits into from
Mar 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 8 additions & 0 deletions core/src/main/scala/cats/syntax/foldable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,14 @@ final class FoldableOps0[F[_], A](private val fa: F[A]) extends AnyVal {
def maximumByOption[B: Order](f: A => B)(implicit F: Foldable[F]): Option[A] =
F.maximumOption(fa)(Order.by(f))

/**
* Equivalent to foldMapM.
* The difference is that foldMapA only requires G to be an Applicative
* rather than a Monad. It is also slower due to use of Eval.
*/
def foldMapA[G[_], B](f: A => G[B])(implicit F: Foldable[F], G: Applicative[G], B: Monoid[B]): G[B] =
F.foldRight(fa, Eval.now(G.pure(B.empty)))((a, egb) => G.map2Eval(f(a), egb)(B.combine)).value

/**
* Implementers are responsible for ensuring they maintain consistency with foldRight; this is not checked by laws on Scala 2.11
*/
Expand Down
12 changes: 12 additions & 0 deletions tests/src/test/scala/cats/tests/FoldableSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,18 @@ class FoldableSuiteAdditional extends CatsSuite {
(Some(x): Option[String])
}
assert(sumMapM == Some("AaronBettyCalvinDeirdra"))

// foldMapM should short-circuit and not call the function when not necessary
val f = (_: String) match {
case "Calvin" => None
case "Deirdra" =>
fail: Unit // : Unit ascription suppresses unreachable code warning
None
case x => Some(x)
}
names.foldMapM(f)
names.foldMapA(f)

val isNotCalvin: String => Option[String] =
x => if (x == "Calvin") None else Some(x)
val notCalvin = F.foldM(names, "") { (acc, x) =>
Expand Down