假设:
// Given an HList of size N, provide evidence of the sum of HList
// multiplied by _3 (length) :: _2 (length) :: _1 (length) :: HNil
// Example: input: _1 :: _2 :: _2 -> output: _3 + _4 + _2 :: HNil
trait HListProductZipped[L <: HList] {
type Out <: HList
}
object HListProductZipped {
type Aux[L <: HList, Out1 <: HList] = HListProductZipped[L] { type Out = Out1 }
def apply[L <: HList](implicit ev: HListProductZipped[L]): Aux[L, ev.Out] = ev
implicit def induct[H <: Nat, T <: HList, L <: Nat](
implicit ev: Length.Aux[H :: T, L],
prod: Prod[H, L],
rest: HListProductZipped[T]
): HListProductZipped.Aux[H :: T, prod.Out :: rest.Out] = new HListProductZipped[H :: T] {
type Out = prod.Out :: rest.Out
}
implicit val hnilHListProductZipped: HListProductZipped[HNil] = new
HListProductZipped[HNil] {
type Out = HNil
}
}
然而,它没有像我预期的那样工作:
import shapeless._
import nat._
import net.HListProductZipped
scala> val a = HListProductZipped[_1 :: _2 :: HNil]
a: net.HListProductZipped[shapeless.::[shapeless.Succ[shapeless._0],shapeless.::[shapeless.Succ[shapeless.Succ[shapeless._0]],shapeless.HNil]]]{type Out = shapeless.::[shapeless.Succ[shapeless.Succ[shapeless._0]],shapeless.::[shapeless.Succ[shapeless.Succ[shapeless._0]],net.HListProductZipped.hnilHListProductZipped.Out]]} = net.HListProductZipped$$anon$3@130efbff
scala> val e: a.Out = _2 :: _2 :: HNil
<console>:19: error: type mismatch;
found : shapeless.::[shapeless.nat._2,shapeless.::[shapeless.nat._2,shapeless.HNil]]
(which expands to) shapeless.::[shapeless.Succ[shapeless.Succ[shapeless._0]],shapeless.::[shapeless.Succ[shapeless.Succ[shapeless._0]],shapeless.HNil]]
required: a.Out
(which expands to) shapeless.::[shapeless.Succ[shapeless.Succ[shapeless._0]],shapeless.::[shapeless.Succ[shapeless.Succ[shapeless._0]],net.HListProductZipped.hnilHListProductZipped.Out]]
val e: a.Out = _2 :: _2 :: HNil
^
请让我知道我做错了什么。
答案 0 :(得分:3)
您遗漏了hnilHListProductZipped
的返回类型中的细化,这意味着编译器无法知道其Out
是HNil
。将其更改为Aux[HNil, HNil]
将使此工作正常。