简体   繁体   中英

Map for generic HList

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](...) )?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM