Search code examples
scalaimplicitshapeless

Shapeless deconstruct tuple in type parameter declaration


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
}

Solution

  • 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
    }