Skip to content

Commit a0b4272

Browse files
arnoldlackozalbia
authored andcommitted
new ZPure constructor 'modifyEither' (#445)
1 parent 87e5d82 commit a0b4272

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

core/shared/src/main/scala/zio/prelude/fx/ZPure.scala

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,15 @@ object ZPure {
716716
def modify[S1, S2, A](f: S1 => (S2, A)): ZPure[S1, S2, Any, Nothing, A] =
717717
Modify(f)
718718

719+
/**
720+
* Constructs a computation that may fail from the specified modify function.
721+
*/
722+
def modifyEither[S1, S2, E, A](f: S1 => Either[E, (S2, A)]): ZPure[S1, S2, Any, E, A] =
723+
get.map(f).flatMap {
724+
case Left(e) => ZPure.fail(e)
725+
case Right((s2, a)) => ZPure.succeed(a).asState(s2)
726+
}
727+
719728
/**
720729
* Constructs a computation that extracts the second element of a tuple.
721730
*/

core/shared/src/test/scala/zio/prelude/fx/ZPureSpec.scala

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -603,7 +603,15 @@ object ZPureSpec extends DefaultRunnableSpec {
603603
assert(ZPure.fromEffect("a".toInt).runEither(()))(
604604
isLeft(equalTo(exception))
605605
)
606-
}
606+
},
607+
suite("modifyEither")(
608+
test("success") {
609+
assert(ZPure.modifyEither((_: Int) => Right((1, "success"))).run(0))(equalTo((1, "success")))
610+
},
611+
test("failure") {
612+
assert(ZPure.modifyEither((_: Int) => Left("error")).runEither(0))(isLeft(equalTo("error")))
613+
}
614+
)
607615
)
608616
)
609617
)

0 commit comments

Comments
 (0)