简体   繁体   中英

Zip generic HList with static Nat HList

I'm searching a way to zip two HList together. The first one is generated from a case class converted in its generic representation, and the second one is defined manually as an HList of Nat.

As a result, I expect a tuple (or 2-members HList) with one field from the case class, and the Nat associated.

The goal is to create a "customizable" ZipWithIndex .

def derive[A, I <: HList, R <: HList, Z <: HList](implicit 
  gen: Generic.Aux[A, R],
  zipper: Zip.Aux[R, I, Z],
  enc: Lazy[Encoder[Z]])(a: A): Deriver[A] = {
    val genRepr = gen.to(A)
    val zipped = zip(genRepr :: ??? :: HNil)
    enc.value(zipped)
}

case class Foo(a: String, b: String, c: String)
derive[Foo, Nat._1 :: Nat._3 :: Nat.7 :: HNil]

The result will have to match an encoderTuple[H, N <: Nat, T <: HList]: Encoder[(H, N) :: T] or and encoderHList[H, N <: Nat, T <: HList]: Encoder[(H::N::HNil) :: T] .

The goal is to create a "customizable" ZipWithIndex .

I guess standard shapeless.ops.hlist.Zip should be enough for that:

  trait Encoder[Z] {
    type Out
    def apply(z: Z): Out
  }

  object Encoder {
    type Aux[Z, Out0] = Encoder[Z] { type Out = Out0 }

    // implicits
  }

  trait Deriver[A]

  object Deriver {
    // implicits
  }

  def derive[A, I <: HList, R <: HList, Z <: HList](a: A, i: I)(implicit
                                                    gen: Generic.Aux[A, R],
                                                    zipper: Zip.Aux[R :: I :: HNil, Z],
                                                    enc: Lazy[Encoder.Aux[Z, Deriver[A]]]): Deriver[A] = {
    val genRepr: R = gen.to(a)
    val zipped: Z = zipper(genRepr :: i :: HNil)
    enc.value(zipped)
  }

  case class Foo(a: String, b: String, c: String)
//  derive[Foo, Nat._1 :: Nat._3 :: Nat._7 :: HNil, ???, ???]
  derive(Foo("aaa", "bbb", "ccc"), Nat._1 :: Nat._3 :: Nat._7 :: HNil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM