Samuel Samuel -4 years ago 83
Scala Question

Shapeless - Apply factory functions with HList

I have a bunch of factory functions that all take the same args and return a different type. Currently I invoke them all explicitly, but it's very verbose, and I want to genericize the factories into a

HList
and invoke each by mapping the
HList
.

case class Endpoint[A](a: A)

case class Factory[Ret](f: Int => Endpoint[Ret])

val factories = Factory[Int](a => Endpoint(a)) :: Factory[String](a => Endpoint(a.toString)) :: HNil


I have defined a
Poly1
so that I can map my
HList
and apply
f
for each element

case class ApplyFactory(param: Int) extends Poly1 {
implicit def generic[A]: Case.Aux[Factory[A], Endpoint[A]] =
at((factory: Factory[A]) => factory.f(param))
}

val endpoints = factories.map(ApplyFactory(5))


The problem is that
could not find implicit value for parameter mapper
. Changing
ApplyFactory
to an object makes the code compile. How do I map over an
HList
if the
Poly
is defined as a class not an object? Or is there a better pattern for applying an
HList
of functions with a given set of parameters and returning a new
HList
with the result?

Answer Source

Don't bother with Poly, just implemented whatever custom map you need by hand:

trait FactoryMap[L <: HList] {
  type Out <: HList
  def map(i: Int, h: L): Out
}

object FactoryMap {
  type Aux[L <: HList, O <: HList] = FactoryMap[L] { type Out = O }

  implicit def caseNil: Aux[HNil, HNil] = new FactoryMap[HNil] {
    type Out = HNil
    def map(i: Int, l: HNil): HNil = l
  }

  implicit def caseCons[T <: HList, O <: HList]
    (implicit ev: Aux[T, O]) = new FactoryMap[Factory[Int] :: T] {
      type Out = Endpoint[Int] :: O
      def map(i: Int, l: Factory[Int] :: T): Endpoint[Int] :: O = {
        val (h :: t) = l
        h.f(i) :: ev.map(i, t)
      }
    }
}

implicit case class MyMap[L <: HList](l: L) {
  def customMap[O <: HList](i: Int)(implicit ev: FactoryMap.Aux[L, O]): O =
    ev.map(i, l)
}

Unlike with Poly, generalizing the above to any Ret (and not Ret = Int like I did) is relatively straightforward.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download