Type-level constraint on HList, extract function domain

Viewed 62

I am writing a combinator that takes in an HList of Option[A] :: Option[AA] :: Option[AAA]... etc.

It also takes a functionf of type A,AA, AAA,... => U. And it returns U. How do I encode the type signature for my combinator? I need to assume my A, AA, AAA are also Monoids so if my options are None, I can call on Monoid zero to create values for f. I am new to shapeless so thank you!

This is what I have so far, but I am missing a lot of constraints.

  1. Every element of H is an Option[A], Option[AA], ...
  2. A, AA, AAA are all Monoids.
  3. The HList D is just the same as H without the Option.
def combinator[H <: HList, D <: HList, U](in: H, f : D => U) : U =
  f(in map { 
    case None : Option[A] => implicitly[Monoid[A]].zero
    case Some(v) => v
  })
1 Answers

Try

  import shapeless.{HList, ::, HNil, Id, Poly1}
  import shapeless.ops.hlist.{Comapped, LiftAll, Mapper, NatTRel}
  import cats.Monoid
  import cats.syntax.option._
  import cats.instances.int._
  import cats.instances.string._
  import cats.instances.double._

  object monoidPoly extends Poly1 {
    implicit def cse[A: Monoid]: Case.Aux[Option[A], A] = at {
      case None => implicitly[Monoid[A]].empty
      case Some(v) => v
    }
  }

  def combinator[H <: HList, D <: HList, U](in: H, f: D => U)(
    implicit
//    comapped: Comapped.Aux[H, Option, D],
//    natTRel: NatTRel[H, Option, D, Id],
//    liftAll: LiftAll[Monoid, D],
    mapper: Mapper.Aux[monoidPoly.type, H, D]
  ): U =
    f(in map monoidPoly)

  combinator(1.some :: none[String] :: 2.0.some :: HNil, (_ : Int :: String :: Double :: HNil).toString)
  // "1 ::  :: 2.0 :: HNil"
Related