Julien Lafont
Julien Lafont

Reputation: 7877

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].

Upvotes: 3

Views: 113

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51658

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)

Upvotes: 1

Related Questions