Search code examples
scalatuplesshapelesspack

Is there a good way to merge two n-tuples?


I have 2 n-tuples and I need to merge their values as parameters for a function foo. Currently I used a Array to save the merged values, which make the function call looks stupid. I wonder if there is a good way to merge the 2 n-tuples, like saving the result into a new n-tuple (then I'll be able to call the function like foo.tupled(mergedT)).

def foo(p1: T, p2: T, p3: T, p4: T) = { ... }
val T1 = ... // a 8-tuple
val T2 = ... // a 8-tuple
def mergeValue[T](x: T, y: T): T = { ... }

val mv = T1.productIterator.zip(T2.productIterator).map(pair => mergeValue(pair._1, pair._2)).toArray
foo(mv(0), mv(1), mv(2), mv(3), mv(4), mv(5), mv(6), mv(7))

Solution

  • This can be done with Shapeless.

    Try

    type T = String
    def foo(p1: T, p2: T, p3: T, p4: T, p5: T, p6: T, p7: T, p8: T) = p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8
    val T1 = ("0", "1", "2", "3", "4", "5", "6", "7")
    val T2 = ("a", "b", "c", "d", "e", "f", "g", "h")
    
    def mergeValue[T](x: T, y: T): T = ???
    
    import shapeless.poly.->, shapeless.syntax.std.tuple._
    
    object p extends ((T, T) -> T)((mergeValue[T] _).tupled)
    
    (foo _).tupled(T1.zip(T2).map(p))