Skip to content

Instantly share code, notes, and snippets.

@mergeconflict
Created May 28, 2013 18:16
Show Gist options
  • Save mergeconflict/5664866 to your computer and use it in GitHub Desktop.
Save mergeconflict/5664866 to your computer and use it in GitHub Desktop.
"dependency injection" monad (for the lulz)
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 }
}
@viktorklang
Copy link

def ask[E]: Inject[E, E] = Inject { identity }

:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment