foldRight后的无形HList地图

时间:2015-10-22 22:40:53

标签: scala implicit shapeless

类型级别foldRight正常工作(getLabelWithValues),后续类型级别map(getValues)也可以正常工作。如果我在一个方法(getValuesFull)中组合两者,它就不再起作用了。丢失的是什么?

完整的源代码(带有隐式调试输出的sbt准备好~run)位于:AndrasDeak

case class Label[A](name: String)
case class LabelWithValue[A](label: Label[A], value: A)

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

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

object GetLabelValue extends (LabelWithValue ~> Id) {
  def apply[B](labelWithValue: LabelWithValue[B]) = labelWithValue.value
}

val labelsWithValues: LabelWithValue[Int] :: HNil = getLabelWithValues(labels)
// manually mapping it works fine:
val valuesManual: Int :: HNil = labelsWithValues.map(GetLabelValue)

// using a second function with Mapper works fine:
val valuesSecondFn: Int :: HNil = getValues(labelsWithValues)

// error: could not find implicit value for parameter mapper: shapeless.ops.hlist.Mapper.Aux[Main.GetLabelValue.type,WithValues,Values]
// val valuesFull: Int :: HNil = getValuesFull(labels)


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

def getValues[WithValues <: HList, Values <: HList](withValues: WithValues)(
  implicit mapper: Mapper.Aux[GetLabelValue.type, WithValues, Values]
): Values = {
  withValues.map(GetLabelValue)
}

def getValuesFull[L <: HList, P, WithValues <: HList, Values <: HList](labels: L)(
  implicit folder: RightFolder.Aux[L, (HNil.type, Map[String, Any]), combineLabelWithValue.type, P],
  ic: IsComposite.Aux[P, WithValues, _],
  mapper: Mapper.Aux[GetLabelValue.type, WithValues, Values]
): Values = {
  val state = Map("a" -> 5, "b" -> "five")
  val resultTuple = labels.foldRight((HNil, state))(combineLabelWithValue)
  val withValues: WithValues = ic.head(resultTuple)
  withValues.map(GetLabelValue)
}

1 个答案:

答案 0 :(得分:6)

此处的问题是,您最终会尝试映射HList HNil静态输入为HNil.type的位置。这通常不起作用 - 例如。在这样的简化案例中:

import shapeless._, ops.hlist.Mapper

val mapped1 = Mapper[poly.identity.type, HNil]
val mapped2 = Mapper[poly.identity.type, HNil.type]

mapped1会编译,但mapped2赢了

诀窍是将HNil.type类型中的RightFolder更改为HNil,然后使用foldRight来呼叫HNil: HNil。这将使一切正常。

我还提出了一些其他建议(使用P代替IsComposite而不是使用Aux来构建元组,跳过mapper上的mapper.Out和返回Value而不是http://www.themusicartists.com/index.php/Artist/Reviews-11类型参数等),但它们可能超出了此问题的范围。