Last active
April 30, 2018 09:06
-
-
Save sungjk/d936090f04aa7ad3c4a25e28613392eb to your computer and use it in GitHub Desktop.
MonadTransformer
This file contains 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
import scala.concurrent.Future | |
import scala.language.higherKinds | |
sealed trait Monad[T[_]] { | |
def map[A, B](value: T[A])(f: A => B): T[B] | |
def flatMap[A, B](value: T[A])(f: A => T[B]): T[B] | |
def pure[A](x: A): T[A] | |
} | |
object MonadT { | |
case class OptionT[T[_], A](value: T[Option[A]])(implicit m: Monad[T]) { | |
def map[B](f: A => B): OptionT[T, B] = OptionT[T, B](m.map(value)(_.map(f))) | |
def flatMap[B](f: A => OptionT[T, B]): OptionT[T, B] = { | |
val result: T[Option[B]] = m.flatMap(value) { a => a.map(b => f(b).value).getOrElse(m.pure(None)) } | |
OptionT[T, B](result) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test on repl