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 foldMapA as an alternative to foldMapM that only requires an Applicative rather than a monad #3130

Merged
merged 1 commit into from
Nov 9, 2019
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/Foldable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,14 @@ import Foldable.sentinel
def foldMapM[G[_], A, B](fa: F[A])(f: A => G[B])(implicit G: Monad[G], B: Monoid[B]): G[B] =
foldM(fa, B.empty)((b, a) => G.map(f(a))(B.combine(b, _)))

/**
* 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.
Copy link
Contributor

Choose a reason for hiding this comment

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

Do we actually know that this is true? My intuition is that it generally will be, but there's also some Either overhead involved in the tailRecM implementation.

*/
def foldMapA[G[_], A, B](fa: F[A])(f: A => G[B])(implicit G: Applicative[G], B: Monoid[B]): G[B] =
foldRight(fa, Eval.now(G.pure(B.empty)))((a, egb) => G.map2Eval(f(a), egb)(B.combine)).value

/**
* Traverse `F[A]` using `Applicative[G]`.
*
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 with ScalaVersionSpecificFoldabl
(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