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

Add EitherT.fromOption #1327

Merged
merged 1 commit into from
Aug 24, 2016
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
18 changes: 18 additions & 0 deletions core/src/main/scala/cats/data/EitherT.scala
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,24 @@ trait EitherTFunctions {
def apply[E, A](either: Either[E, A])(implicit F: Applicative[F]): EitherT[F, E, A] =
EitherT(F.pure(either))
}

/** Transforms an `Option` into an `EitherT`, lifted into the specified `Applicative` and using
* the second argument if the `Option` is a `None`.
* {{{
* scala> import cats.implicits._
* scala> val o: Option[Int] = None
* scala> EitherT.fromOption[List](o, "Answer not known.")
* res0: EitherT[List, String, Int] = EitherT(List(Left(Answer not known.)))
* scala> EitherT.fromOption[List](Some(42), "Answer not known.")
* res1: EitherT[List, String, Int] = EitherT(List(Right(42)))
Copy link
Contributor Author

Choose a reason for hiding this comment

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

  1. In the doctests

* }}}
*/
final def fromOption[F[_]]: FromOptionPartiallyApplied[F] = new FromOptionPartiallyApplied

final class FromOptionPartiallyApplied[F[_]] private[EitherTFunctions] {
def apply[E, A](opt: Option[A], ifNone: => E)(implicit F: Applicative[F]): EitherT[F, E, A] =
EitherT(F.pure(Either.fromOption(opt, ifNone)))
}
}

private[data] abstract class EitherTInstances extends EitherTInstances1 {
Expand Down
6 changes: 6 additions & 0 deletions tests/src/test/scala/cats/tests/EitherTTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,12 @@ class EitherTTests extends CatsSuite {
}
}

test("fromOption isLeft consistent with Option.isEmpty") {
forAll { (o: Option[Int], s: String) =>
EitherT.fromOption[Id](o, s).isLeft should === (o.isEmpty)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

  1. In the test

}
}

test("isLeft negation of isRight") {
forAll { (eithert: EitherT[List, String, Int]) =>
eithert.isLeft should === (eithert.isRight.map(! _))
Expand Down