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

Implement Reducible.reduceM #1193

Merged
merged 1 commit into from
Jul 15, 2016
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
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))


}