Created
February 10, 2016 22:58
-
-
Save raulraja/a38b99816020d2bce5fb to your computer and use it in GitHub Desktop.
Shapeless autolifting Kleisli#local to avoid lambda boilerplate
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
import cats._ | |
import cats.data._ | |
import shapeless._ | |
import shapeless.ops.hlist.Selector | |
implicit class ReaderOps[A, B, L <: HList](f: Reader[A, B]) { | |
def liftD[AA](implicit ga: Generic.Aux[AA, L], sel: Selector[L, A]): Reader[AA, B] = | |
f.local[AA](aa => sel.apply(ga.to(aa))) | |
} | |
case class Dep1(msg: String) | |
case class Dep2(amount: Int) | |
case class Config(dep: Dep1, dep2: Dep2) | |
implicit val module: Config = Config(Dep1("It's a : "), Dep2(10)) | |
def service1: Reader[Dep1, String] = Reader { d1: Dep1 => d1.msg } | |
def service2: Reader[Dep2, Int] = Reader { d2: Dep2 => d2.amount } | |
val composed = for { | |
a <- service1.liftD[Config] // no need to provide local manual boilerplate | |
b <- service2.liftD[Config] | |
} yield a + b | |
composed.run(module) | |
// res0: cats.Id[String] = It's a : 10 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment