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

Enable breakout in functions nonEmptyTraverse_ and nonEmptySequence_ #3545

Merged
merged 2 commits into from
Aug 4, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 2 additions & 2 deletions core/src/main/scala/cats/Reducible.scala
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ import scala.annotation.implicitNotFound
* the traversal.
*/
def nonEmptyTraverse_[G[_], A, B](fa: F[A])(f: A => G[B])(implicit G: Apply[G]): G[Unit] =
G.void(reduceLeftTo(fa)(f)((x, y) => G.map2(x, f(y))((_, b) => b)))
G.void(reduceRightTo(fa)(f)((x, y) => G.map2Eval(f(x), y)((_, b) => b)).value)
Copy link
Contributor

@johnynek johnynek Aug 3, 2020

Choose a reason for hiding this comment

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

should we not void after each f? couldn't that be a win rather than voiding at the end?

f1 = f.andThen(G.void(_))

or:

val f1 = f.andThen(G.void(_))
G.void(reduceRightTo(fa)(f1)((x, y) => G.map2Eval(G.void(f(x)), y)((_, b) => b)).value)


/**
* Sequence `F[G[A]]` using `Apply[G]`.
Expand All @@ -192,7 +192,7 @@ import scala.annotation.implicitNotFound
* [[nonEmptyTraverse_]] documentation for a description of the differences.
*/
def nonEmptySequence_[G[_], A](fga: F[G[A]])(implicit G: Apply[G]): G[Unit] =
G.void(reduceLeft(fga)((x, y) => G.map2(x, y)((_, b) => b)))
nonEmptyTraverse_(fga)(identity)

def toNonEmptyList[A](fa: F[A]): NonEmptyList[A] =
reduceRightTo(fa)(a => NonEmptyList(a, Nil)) { (a, lnel) =>
Expand Down
11 changes: 10 additions & 1 deletion tests/src/test/scala/cats/tests/ReducibleSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,16 @@ class ReducibleSuiteAdditional extends CatsSuite {

notAllEven.reduceMapA { a => out += a; if (a % 2 == 0) Some(a) else None }

assert(out.toList === (List(2, 4, 6, 9)))
assert(out.toList === List(2, 4, 6, 9))
}

test("Reducible[NonEmptyList].nonEmptyTraverse_ can breakout") {
val notAllEven = NonEmptyList.of(2, 4, 6, 9, 10, 12, 14)
val out = mutable.ListBuffer[Int]()

notAllEven.nonEmptyTraverse_ { a => out += a; if (a % 2 == 0) Some(a) else None }

assert(out.toList === List(2, 4, 6, 9))
}

// A simple non-empty stream with lazy `foldRight` and `reduceRightTo` implementations.
Expand Down