0

I am working through the excellent Scala with Cats and I'm not sure about Monad transformers. Specifically, there is an example that goes

type ErrorOr[A] = Either[String, A]
type ErrorOrOption[A] = OptionT[ErrorOr, A]
val a = 10.pure[ErrorOrOption] // a: OptionT(Right(Some(10)))
val b = 32.pure[ErrorOrOption] // b: OptionT(Right(Some(32)))
val c = a.flatMap(x => b.map(y => x + y)) // c: OptionT(Right(Some(42)))
  • How could I create an empty option?

    // d: OptionT(Right(None))
    
  • How could I create an error value?

    // e: OptionT(Left("A terrible error."))
    
  • Is it correct that if I mapped over those the propagated value would be a Left?

Thanks.

ticofab
  • 7,551
  • 13
  • 49
  • 90

1 Answers1

1

I got it, I needed to use apply.

val e = OptionT[ErrorOr, Int](Right(None))
val d = OptionT[ErrorOr, Int](Left("A terrible error."))
val f = for {
    e1 <- d
    e2 <- e
  } yield e1 + e2 // f: OptionT(Left(A terrible error.))

val g = 10.pure[ErrorOrOption]
val h = OptionT[ErrorOr, Int](Right(None))
val i = for {
    e1 <- g
    e2 <- h
  } yield e1 + e2 // i: OptionT(Right(None))
ticofab
  • 7,551
  • 13
  • 49
  • 90