Skip to content

Instantly share code, notes, and snippets.

@joan38
Created March 27, 2017 21:57
Show Gist options
  • Save joan38/e4267a61a793d076567827176b161e19 to your computer and use it in GitHub Desktop.
Save joan38/e4267a61a793d076567827176b161e19 to your computer and use it in GitHub Desktop.
case class Param[T](name: String)
trait ParamDecoder[T] {
def apply(in: String): T
}
object ParamDecoder {
implicit val stringDecoder = new ParamDecoder[String] { def apply(in: String) = in }
implicit val intDecoder = new ParamDecoder[Int] { def apply(in: String) = in.toInt }
}
object fetchFromContext extends Poly1 {
implicit def forParam[T](implicit decode: ParamDecoder[T]) = at[(Param[T], Map[String, String])] { case (p, c) =>
decode(c(p.name))
}
}
case class Job[H <: HList, F, P <: HList, L <: Nat, C <: HList, HC <: HList](params: H)(f: F)(
implicit l: Length.Aux[H, L],
contexts: Fill.Aux[L, Map[String, String], C],
zipped: Zip.Aux[H :: C :: HNil, HC],
mapper: Mapper.Aux[fetchFromContext.type, HC, P],
fToProd: FnToProduct.Aux[F, P => Unit]
) {
def run(context: Map[String, String]): Unit = {
val contextHList = contexts.apply(context) // C, i.e. Map[String, String] :: Map[String, String] :: HNil
val fetchedParams = params // H, i.e. Param[A] :: Param[B] :: HNil
.zip(contextHList) // HC, i.e. (Param[A], Map[String, String]) :: (Param[B], Map[String, String]) :: HNil
.map(fetchFromContext) // P, i.e. A :: B :: HNil
fToProd(f)(fetchedParams)
}
}
val testJob = Job(
Param[String]("foo") ::
Param[Int]("bar") ::
Param[Int]("baz") ::
HNil) { (s: String, i1: Int, i2: Int) =>
println(s + ": " + (i1 + i2))
}
testJob.run(Map("foo" -> "Result", "bar" -> "12", "baz" -> "2"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment