Skip to content

Commit

Permalink
Merge pull request #1193 from benhutchison/topic/reduceM
Browse files Browse the repository at this point in the history
Implement Reducible.reduceM
  • Loading branch information
ceedubs authored Jul 15, 2016
2 parents 5455ff1 + 1b954ed commit b304dfc
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
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))
}

}


0 comments on commit b304dfc

Please sign in to comment.