Skip to content

Commit

Permalink
new ZPure constructor 'modifyEither' (#445)
Browse files Browse the repository at this point in the history
  • Loading branch information
arnoldlacko authored Nov 26, 2020
1 parent c817ec9 commit a749622
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
9 changes: 9 additions & 0 deletions core/shared/src/main/scala/zio/prelude/fx/ZPure.scala
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,15 @@ object ZPure {
def modify[S1, S2, A](f: S1 => (S2, A)): ZPure[S1, S2, Any, Nothing, A] =
Modify(f)

/**
* Constructs a computation that may fail from the specified modify function.
*/
def modifyEither[S1, S2, E, A](f: S1 => Either[E, (S2, A)]): ZPure[S1, S2, Any, E, A] =
get.map(f).flatMap {
case Left(e) => ZPure.fail(e)
case Right((s2, a)) => ZPure.succeed(a).asState(s2)
}

/**
* Constructs a computation that extracts the second element of a tuple.
*/
Expand Down
10 changes: 9 additions & 1 deletion core/shared/src/test/scala/zio/prelude/fx/ZPureSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,15 @@ object ZPureSpec extends DefaultRunnableSpec {
assert(ZPure.fromEffect("a".toInt).runEither(()))(
isLeft(equalTo(exception))
)
}
},
suite("modifyEither")(
test("success") {
assert(ZPure.modifyEither((_: Int) => Right((1, "success"))).run(0))(equalTo((1, "success")))
},
test("failure") {
assert(ZPure.modifyEither((_: Int) => Left("error")).runEither(0))(isLeft(equalTo("error")))
}
)
)
)
)
Expand Down

0 comments on commit a749622

Please sign in to comment.