Skip to content
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
6 changes: 6 additions & 0 deletions core/src/main/scala/cats/Reducible.scala
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ import simulacrum.typeclass
*/
def reduceLeftTo[A, B](fa: F[A])(f: A => B)(g: (B, A) => B): B

/**
* Monadic variant of [[reduceLeftTo]]
*/
def reduceLeftM[G[_], A, B](fa: F[A])(f: A => G[B])(g: (B, A) => G[B])(implicit G: FlatMap[G]): G[B] =
reduceLeftTo(fa)(f)((gb, a) => G.flatMap(gb)(g(_, a)))

/**
* Overriden from Foldable[_] for efficiency.
*/
Expand Down
18 changes: 18 additions & 0 deletions tests/src/test/scala/cats/tests/ReducibleTests.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package cats
package tests

class ReducibleTestsAdditional extends CatsSuite {

test("Reducible[NonEmptyList].reduceLeftM stack safety") {
def nonzero(acc: Long, x: Long): Option[Long] =
if (x == 0) None else Some(acc + x)

val n = 100000L
val expected = n*(n+1)/2
val actual = (1L to n).toList.toNel.flatMap(_.reduceLeftM(Option.apply)(nonzero))
actual should === (Some(expected))
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This should be fine since (1L to n).toList.toNel should never return None, but I think I'd rather either see it explicitly use Option.get or do something like:

val actual = (1L to n).toList.toNel.flatMap(_.reduceM(Option.apply)(nonzero))
actual should === (Some(expected))


}