Search code examples
scalamonadsscala-optionenrich-my-libraryflatmap

How to implement flatMap for Option


I'm trying to implement map and flatMap as an extension/enrichment for Option, without cheating and looking at how it was implemented in Scalaz.

So here's what I got so far before I got stuck:

package extensions.monad

trait Monad[M[_]] {
  // >>= :: Monad m => m a -> (a -> m b) -> m b
  def flatMap[A, B](input: A => M[B]): M[B]
}

trait Functor[F[_]] {
  // fmap :: Functor f => (a -> b) -> f a -> f b
  def map[A, B](input: A => B): F[B]
}

object MOption {
  implicit class MonadicOption[A](left: Option[A]) extends Monad[Option[A]] with Functor[Option[A]] {
    def flatMap[A, B](right: A => Option[B]): Option[B] = ???

    def map[A, B](right: A => B): Option[B] = ???
  }
}

All I really need is the basic functionality, so I can do something like this:

Some(3).flatMap(x => Some(4).map(y => x + y))

Any hints?


Solution

  • def flatMap[A, B](right: A => Option[B]): Option[B] = left match {
      None => None
      Some(x) => right(x)
    }
    

    or similarly to what the scala std library does

    def flatMap[A, B](right: A => Option[B]): Option[B] =
      if (left.isEmtpy) None else right(left.get)