Skip to content

Commit

Permalink
Implement Reducible.reduceM
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben Hutchison committed Jul 14, 2016
1 parent 579e0b4 commit e089220
Show file tree
Hide file tree
Showing 2 changed files with 26 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 reduceM[G[_], A, B](fa: F[A])(f: A => G[B])(g: (B, A) => G[B])(implicit G: Monad[G]): G[B] =
reduceLeftTo(fa)(f)((gb, a) => G.flatMap(gb)(g(_, a)))

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

class ReducibleTestsAdditional extends CatsSuite {

test("Reducible[NonEmptyList].reduceM 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
(1L to n).toList.toNel.foreach { nel =>
val actual = nel.reduceM(Option.apply)(nonzero)
assert(actual.get == expected)
}
}

}


0 comments on commit e089220

Please sign in to comment.