From 1b954edf40a19ff7f116667b4484b307b79f8b92 Mon Sep 17 00:00:00 2001 From: Ben Hutchison Date: Thu, 14 Jul 2016 10:45:05 +1000 Subject: [PATCH] Implement Reducible.reduceLeftM --- core/src/main/scala/cats/Reducible.scala | 6 ++++++ .../test/scala/cats/tests/ReducibleTests.scala | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 tests/src/test/scala/cats/tests/ReducibleTests.scala diff --git a/core/src/main/scala/cats/Reducible.scala b/core/src/main/scala/cats/Reducible.scala index fb6cfe1c71..e2b11d813b 100644 --- a/core/src/main/scala/cats/Reducible.scala +++ b/core/src/main/scala/cats/Reducible.scala @@ -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. */ diff --git a/tests/src/test/scala/cats/tests/ReducibleTests.scala b/tests/src/test/scala/cats/tests/ReducibleTests.scala new file mode 100644 index 0000000000..ede3ac68b9 --- /dev/null +++ b/tests/src/test/scala/cats/tests/ReducibleTests.scala @@ -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)) + } + +} + +