0

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?

Electric Coffee
  • 11,733
  • 9
  • 70
  • 131
  • 1
    I would start by defining Monad correctly. Where is `const` (or `return` or however you want to call it)? – kiritsuku Sep 09 '14 at 21:54
  • @sschaef I only went by the most basic functionality, namely the `bind` (here `flatMap`) function of the monad, I'd bother with `return` when I got to it – Electric Coffee Sep 09 '14 at 21:55
  • 1
    you don't want cheating by looking at scalaz, and yet you ask for a solution on SO? I don't get it. – Gabriele Petronella Sep 09 '14 at 21:55
  • @GabrielePetronella I have my reasons, maybe SO had a better/simpler solution given the fact that I didn't want the full functionality found in scalaz's implementation – Electric Coffee Sep 09 '14 at 21:57
  • 1
    The most basic functionality of a monad is `bind` and `const`. You can't implement a monad when one of them is missing. – kiritsuku Sep 09 '14 at 21:57
  • Agree with the comments here, a Monad *by definition* must have an "identity element" or "const", whatever you want to call it. Two, I dont see the point in asking SO, when its a very very simple thing to implement and u can just look at the native Scala implementation. – samthebest Sep 10 '14 at 04:32
  • @samthebest I couldn't even find "const" or "identity" in the scalaz implementation – Electric Coffee Sep 10 '14 at 05:47
  • It's `Some` @ElectricCoffee – samthebest Sep 10 '14 at 08:40

1 Answers1

2
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)
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235