Map for generic HList

2019-09-09 01:37发布

Say we have following method

def func[T <: HList](hlist: T, poly: Poly)
    (implicit mapper : Mapper[poly.type, T]): Unit = {
    hlist map poly 
}

and custom Poly

object f extends (Set ~>> String) {
    def apply[T](s : Set[T]) = s.head.toString
}

So I can use this func like

func(Set(1, 2) :: Set(3, 4) :: HNil, f)

In my code I have small number of Polies and a big number of func invocations. For this purpose I tried to move poly: Poly to implicit parameters and got expected message

illegal dependent method type: parameter appears in the type of another parameter in the same section or an earlier one

How could I change or extend poly: Poly parameter to avoid this error (I need to keep type signature func[T <: HList](...))?

1条回答
太酷不给撩
2楼-- · 2019-09-09 02:12

Maybe you could use the "partially applied" trick using a class with an apply method :

import shapeless._
import ops.hlist.Mapper

final class PartFunc[P <: Poly](val poly: P) {
  def apply[L <: HList](l: L)(implicit mapper: Mapper[poly.type, L]): mapper.Out =
    l map poly
}

def func[P <: Poly](poly: P) = new PartFunc(poly)

With your poly f :

val ff = func(f)
ff(Set(1, 2) :: Set(3, 4) :: HNil)          // 1 :: 3 :: HNil
ff(Set("a", "b") :: Set("c", "d") :: HNil)  // a :: c :: HNil
查看更多
登录 后发表回答