scalashapelesshlist

How to concatenate function arguments and return values using shapeless


I was trying to define compose method below:

import shapeless.{::, HList, HNil}

def compose[A1 <: HList, R1, A2 <: HList, R2](f: A1 => R1, g: A2 => R2): R1 :: R2 :: HNil = ???

val f = (xs: Int :: String :: HNil) => xs.select[Int].toString + xs.select[String]
val g = (xs: Boolean :: HNil) => xs.select[Boolean]

// expected output:
// Int :: String :: Boolean :: HNil => String :: Boolean :: HNil
compose(f, g)

This is my incomplete code and I have no idea how to get A1 and A2 from args. Can anyone help, please?

def compose[A1 <: HList, R1, A2 <: HList, R2](f: A1 => R1, g: A2 => R2)(implicit p: Prepend[A2, A1]) =
  (args: p.Out) => {
    val a1: A1 = ???
    val a2: A2 = ???
    f(a1) :: f(a2) :: HNil
  }

Solution

  • I was able to implement a working solution with Split:

    def compose[A1 <: HList, R1, A2 <: HList, R2, O <: HList, N <: Nat](f: A1 => R1, g: A2 => R2)(
      implicit split: Split.Aux[O, N, A1, A2]
    ): O => R1 :: R2 :: HNil = {
      (a: O) =>
        val (a1, a2) = split.apply(a)
        f(a1) :: g(a2) :: HNil //I assumed you meant calling g(a2) here
    }
    
    val f = (xs: Int :: String :: HNil) => xs.select[Int].toString + xs.select[String]
    val g = (xs: Boolean :: HNil) => xs.select[Boolean]
    
    val r: Int :: String :: Boolean :: HNil => String :: Boolean :: HNil = compose(f, g)
    
    println(r.apply(1 :: "hello" :: true :: HNil)) // 1hello :: true :: HNil