Search code examples
scalashapeless

Scala shapeless function corresponding to the vanilla "zipped" on regular lists?


This is a newb question.

I'd like to do something like this:

val a = 1 :: "hi" :: HNil
val b = "foo" :: 2.2 :: HNil
val c = 3 :: 4 :: HNil

val d = (a, b, c).zip // Like "zipped" on tuples of regular lists.

In the above, d should have the value:

(1, "foo", 3) :: ("hi", 2.2, 4) :: HNil

Is there a clean way to do this?


Solution

  • You'll need to convert the tuple to an HList first. In 1.2.x:

    import shapeless._, Tuples._
    
    val a = 1 :: "hi" :: HNil
    val b = "foo" :: 2.2 :: HNil
    val c = 3 :: 4 :: HNil
    
    (a, b, c).hlisted.zipped
    

    In 2.0.0 you have more options:

    import shapeless._, syntax.std.tuple._
    
    val a = 1 :: "hi" :: HNil
    val b = "foo" :: 2.2 :: HNil
    val c = 3 :: 4 :: HNil
    
    (a, b, c).productElements.zip
    

    Or:

    import shapeless._, syntax.std.tuple._
    
    val a = (1, "hi")
    val b = ("foo", 2.2)
    val c = (3, 4)
    
    (a, b, c).zip
    

    This last will return a tuple of 3-tuples, which may or may not work for you.