Map for generic HList

*爱你&永不变心* 提交于 2019-12-12 03:06:45

问题


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:


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


来源:https://stackoverflow.com/questions/38052087/map-for-generic-hlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!