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

IdentityFlatten#when and IdentityFlatten#unless. #1453

Merged
merged 1 commit into from
Jan 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ import zio.test.laws._
object IdentityFlattenSpec extends ZIOBaseSpec {
import zio.prelude.Fixtures._

val genBoolean: Gen[Any, Boolean] =
Gen.boolean

val genInt: Gen[Any, Int] =
Gen.int

val genList: Gen[Sized, List[Int]] =
Gen.listOf(genInt)

def spec: Spec[Environment, Any] =
suite("IdentityFlattenSpec")(
suite("laws")(
Expand All @@ -16,6 +25,22 @@ object IdentityFlattenSpec extends ZIOBaseSpec {
test("option")(checkAllLaws(IdentityFlattenLaws)(GenF.option, Gen.int)),
test("optional")(checkAllLaws(IdentityFlattenLaws)(optionalGenF, Gen.int)),
test("vector")(checkAllLaws(IdentityFlattenLaws)(GenF.vector, Gen.int))
),
suite("combinators")(
test("when") {
check(genList, genBoolean) { (as, b) =>
val actual = as.when(b)
val expected = if (b) as.map(Some(_)) else List(None)
assert(actual)(equalTo(expected))
}
},
test("unless") {
check(genList, genBoolean) { (as, b) =>
val actual = as.unless(b)
val expected = if (b) List(None) else as.map(Some(_))
assert(actual)(equalTo(expected))
}
}
)
)

Expand Down
14 changes: 14 additions & 0 deletions core/shared/src/main/scala/zio/prelude/IdentityFlatten.scala
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,17 @@ object IdentityFlatten {
identityFlatten

}

trait IdentityFlattenSyntax {

/**
* Provides infix syntax for identity operations for covariant types.
*/
implicit class IdentityFlattenCovariantOps[F[+_], A](fa: F[A]) {
def unless(b: => Boolean)(implicit identity: IdentityFlatten[F], covariant: Covariant[F]): F[Option[A]] =
if (b) identity.any.as(None) else fa.map(Some(_))

def when(b: => Boolean)(implicit identity: IdentityFlatten[F], covariant: Covariant[F]): F[Option[A]] =
if (b) fa.map(Some(_)) else identity.any.as(None)
}
}
1 change: 1 addition & 0 deletions core/shared/src/main/scala/zio/prelude/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ package object prelude
with IdExports
with IdentityBothSyntax
with IdentityEitherSyntax
with IdentityFlattenSyntax
with IdentitySyntax
with InvariantSyntax
with InverseSyntax
Expand Down