Skip to content

Instantly share code, notes, and snippets.

@tonymorris
Created March 20, 2014 23:42
Show Gist options
  • Save tonymorris/9676418 to your computer and use it in GitHub Desktop.
Save tonymorris/9676418 to your computer and use it in GitHub Desktop.
Reader compose Option
case class ~=>[T, A](f: T => A) {
def map[B](g: A => B): T ~=> B =
~=>(f andThen g)
def flatMap[B](g: A => T ~=> B): T ~=> B =
~=>(t => g(f(t)).f(t))
}
object ~=> {
// unit: A => F[A]
def constant[T, A](a: A): T ~=> A =
~=>(_ => a)
}
object T {
import ~=>._
// F[A] => (A => F[B]) => F[B]
// let F = T ~=> Option[_]
// (F [A])=> (A => F [B])=>F [B]
def flatMap2[T, A, B](x: T ~=> Option[A], f: A => T ~=> Option[B]): T ~=> Option[B] =
for {
optiona <- x
optionb <- optiona match {
case None => ~=>.constant[T, Option[B]](None)
case Some(a) => f(a)
}
} yield optionb
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment