Skip to content

Instantly share code, notes, and snippets.

@ElectricCoffee
Created September 9, 2014 22:39
Show Gist options
  • Save ElectricCoffee/eb254bfd39c80f17cbfe to your computer and use it in GitHub Desktop.
Save ElectricCoffee/eb254bfd39c80f17cbfe to your computer and use it in GitHub Desktop.
Adds map and flatMap as extension methods to Scala, for those who don't want/need scalaz for their project, is fully compatible with for-comprehensions
package extension.monad
trait Monad[A, M[_]] {
// >>= :: Monad m => m a -> (a -> m b) -> m b
def flatMap[B](input: A => M[B]): M[B] // AKA "bind"
}
trait Functor[A, F[_]] {
// fmap :: Functor f => (a -> b) -> f a -> f b
def map[B](input: A => B): F[B] // AKA "fmap"
}
object MOption {
implicit class MonadicOption[A](left: Option[A]) extends Monad[A, Option] with Functor[A, Option] {
def flatMap[B](right: A => Option[B]): Option[B] = left match {
case Some(x) => right(x)
case None => None
}
def map[B](right: A => B): Option[B] = left match {
case Some(x) => Some(right(x))
case None => None
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment