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 MonadError instance for OptionT where F is a Monad #2228

Closed
LukaJCB opened this issue Apr 13, 2018 · 6 comments
Closed

Add MonadError instance for OptionT where F is a Monad #2228

LukaJCB opened this issue Apr 13, 2018 · 6 comments

Comments

@LukaJCB
Copy link
Member

LukaJCB commented Apr 13, 2018

Currently we have (Monad f) => Monad (OptionT f) as well as (MonadError f e) => MonadError (OptionT f) e, but we could just as well change that first definition to have a MonadError[OptionT[F, ?], Unit]. :)

@LukaJCB
Copy link
Member Author

LukaJCB commented Apr 13, 2018

I've even got a free implementation to give away:

private[effect] trait OptionTMonadError[F[_]] extends MonadError[OptionT[F, ?], Unit] {
  implicit def F: Monad[F]

  def pure[A](a: A): OptionT[F, A] = OptionT.pure(a)

  def flatMap[A, B](fa: OptionT[F, A])(f: A => OptionT[F, B]): OptionT[F, B] = fa.flatMap(f)

  override def map[A, B](fa: OptionT[F, A])(f: A => B): OptionT[F, B] = fa.map(f)

  def tailRecM[A, B](a: A)(f: A => OptionT[F, Either[A, B]]): OptionT[F, B] =
    OptionT(F.tailRecM(a)(a0 => F.map(f(a0).value)(
      _.fold(Either.right[A, Option[B]](None))(_.map(b => Some(b): Option[B]))
    )))

  def raiseError[A](e: Unit): OptionT[F, A] = OptionT.none

  def handleErrorWith[A](fa: OptionT[F, A])(f: Unit => OptionT[F, A]): OptionT[F, A] =
    OptionT(F.flatMap(fa.value) {
      case s @ Some(_) => F.pure(s)
      case None => f(()).value
    })
}

@oleg-py
Copy link

oleg-py commented Apr 13, 2018

Btw, is MonadError[Option, Unit] actually useful?

@LukaJCB
Copy link
Member Author

LukaJCB commented Apr 13, 2018

As useful as it ever as, I wager ;)

@sh-abhi
Copy link

sh-abhi commented May 28, 2018

@LukaJCB I'm new to Cats and would love to help contribute. While I'm not familiar with the code base yet, I'm happy to give this a try if we think it's appropriate for a newcomer?

@LukaJCB
Copy link
Member Author

LukaJCB commented May 29, 2018

Sure, go right ahead, I'll guide you through it if you hit any hurdles! :)

@sh-abhi
Copy link

sh-abhi commented Jul 1, 2018

@LukaJCB, appears that this already had a PR merged. I guess we can go ahead and close this open issue? I'll try to pick up another open one.

@LukaJCB LukaJCB closed this as completed Jul 2, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants