Created
May 28, 2013 18:16
-
-
Save mergeconflict/5664866 to your computer and use it in GitHub Desktop.
"dependency injection" monad (for the lulz)
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
case class Inject[-E, +A](inject: E => A) { | |
// covariant functor and monad | |
def map[B](f: A => B): Inject[E, B] = | |
Inject { e => f(inject(e)) } | |
def flatMap[ε <: E, B](f: A => Inject[ε, B]): Inject[ε, B] = | |
Inject { e => f(inject(e)).inject(e) } | |
// to satisfy for-comprehension desugaring in scala < 2.10 | |
def filter(f: A => Boolean): Inject[E, A] = | |
map { a => if (f(a)) a else throw new MatchError(a) } | |
// contravariant functor: adapt this injector to work on some other environment | |
def module[ε](f: ε => E): Inject[ε, A] = | |
Inject { e => inject(f(e)) } | |
} | |
object Inject { | |
def ask[E]: Inject[E, E] = Inject { e => e } | |
def const[A](a: A): Inject[Any, A] = Inject { _ => a } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
def ask[E]: Inject[E, E] = Inject { identity }
:)