将这样的内容添加到 Shapeless 可能是有意义的:
import shapeless._, ops.hlist.Prepend
trait Range[A <: Nat, B <: Nat] extends DepFn0 { type Out <: HList }
object Range {
type Aux[A <: Nat, B <: Nat, Out0 <: HList] = Range[A, B] { type Out = Out0 }
implicit def emptyRange[A <: Nat]: Aux[A, A, HNil] = new Range[A, A] {
type Out = HNil
def apply(): Out = HNil
}
implicit def slightlyBiggerRange[A <: Nat, B <: Nat, OutAB <: HList](implicit
rangeAB: Aux[A, B, OutAB],
appender: Prepend[OutAB, B :: HNil],
witnessB: Witness.Aux[B]
): Aux[A, Succ[B], appender.Out] = new Range[A, Succ[B]] {
type Out = appender.Out
def apply(): Out = appender(rangeAB(), witnessB.value :: HNil)
}
}
def range[A <: Nat, B <: Nat](implicit r: Range[A, B]): r.Out = r()
现在你可以写zipWithIndex
得很干净了:
import ops.hlist.{ Length, Zip }
def zipWithIndex[L <: HList, S <: Nat, R <: HList, Out <: HList](l: L)(implicit
len: Length.Aux[L, S],
range: Range.Aux[nat._0, S, R],
zipper: Zip.Aux[L :: R :: HNil, Out]
): Out = l.zip(range())
接着:
import nat._
type Expected = (Int, _0) :: (Symbol, _1) :: (String, _2) :: HNil
val xs: Expected = zipWithIndex(1 :: 'a :: "foo" :: HNil)
您还可以使用 fold 或ZippedWithIndex[L <: HList]
type 类,这两者都可能更简洁一些,但不太清楚地由独立有用的部分组成,例如Range
.