Shapeless deconstruct tuple in type parameter declaration

眉间皱痕 提交于 2019-12-06 06:23:52

问题


I am using a RightFolder that returns a Tuple2 and would like to return the _1 part. The first version rightFoldUntupled1 works fine but uses an additional IsComposite typeclass.

In the second version rightFoldUntupled2 I try to achieve the same without IsComposite by destructuring P as a Product2[_, Values]. That doesn't work any more - the compiler is happy to witness that P is a Product2[_,_], but as soon as I use a named type parameter for _1 it doesn't compile any more. Any idea why?

The full source (with sbt ready to ~run with implicit debug output) is here: https://github.com/mpollmeier/shapeless-playground/tree/f3cf049

case class Label[A](name: String)

val label1 = Label[Int]("a")
val labels = label1 :: HNil

object getValue extends Poly2 {
  implicit def atLabel[A, B <: HList] = at[Label[A], (B, Map[String, Any])] {
    case (label, (acc, values)) ⇒
      (values(label.name).asInstanceOf[A] :: acc, values)
  }
}

// compiles fine
val untupled1: Int :: HNil = rightFoldUntupled1(labels)

// [error] could not find implicit value for parameter folder:
// shapeless.ops.hlist.RightFolder.Aux[shapeless.::[Main.DestructureTupleTest.Label[Int],shapeless.HNil],
//(shapeless.HNil, Map[String,Any]),Main.DestructureTupleTest.getValue.type,P]
val untupled2: Int :: HNil = rightFoldUntupled2(labels)

def rightFoldUntupled1[L <: HList, P <: Product2[_, _], Values <: HList](labels: L)(
  implicit folder: RightFolder.Aux[L, (HNil, Map[String, Any]), getValue.type, P],
  ic: IsComposite.Aux[P, Values, _]
): Values = {
  val state = Map("a" -> 5, "b" -> "five")
  val resultTuple = labels.foldRight((HNil: HNil, state))(getValue)
  ic.head(resultTuple)
}

def rightFoldUntupled2[L <: HList, Values, P <: Product2[_, Values]](labels: L)(
  implicit folder: RightFolder.Aux[L, (HNil, Map[String, Any]), getValue.type, P]
): Values = {
  val state = Map("a" -> 5, "b" -> "five")
  val resultTuple = labels.foldRight((HNil: HNil, state))(getValue)
  resultTuple._1
}

回答1:


This should work same as rightFoldUntupled1:

def rightFoldUntupled2[L <: HList, Values, M](labels: L)(
  implicit folder: RightFolder.Aux[L, (HNil, Map[String, Any]), getValue.type, (Values, M)]
  ): Values = {
  val state = Map("a" -> 5, "b" -> "five")
  val resultTuple = labels.foldRight((HNil: HNil, state))(getValue)
  resultTuple._1
}


来源:https://stackoverflow.com/questions/33313164/shapeless-deconstruct-tuple-in-type-parameter-declaration

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