Created
September 9, 2014 22:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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