scala - generic unzip for HList

后端 未结 2 1101
-上瘾入骨i
-上瘾入骨i 2021-01-01 02:12

I have the following Scala problem:

Write a function that will take a list of HLists

List(23 :: “a” :: 1.0d :: HNil, 24 :: “b” :: 2.0d :: HNil)    #          


        
2条回答
  •  生来不讨喜
    2021-01-01 02:57

    To solve this you'll need a custom typeclass:

    import shapeless._
    
    trait Unzipper[ -input ]{
      type Output
      def unzip( input: input ): Output
    }
    object Unzipper {
      implicit def headTail
        [ head, tail <: HList ]
        ( implicit tailUnzipper: Unzipper[ List[ tail ] ]{ type Output <: HList } )
        =
        new Unzipper[ List[ head :: tail ] ]{
          type Output = List[ head ] :: tailUnzipper.Output
          def unzip( list: List[ head :: tail ] ) = 
            list.map(_.head) :: tailUnzipper.unzip(list.map(_.tail))
        }
      implicit val nil =
        new Unzipper[ List[ HNil ] ]{
          type Output = HNil
          def unzip( list: List[ HNil ] ) = HNil
        }
    }
    
    val list = List(23 :: "a" :: 1.0d :: HNil, 24 :: "b" :: 2.0d :: HNil)
    println( implicitly[Unzipper[list.type]].unzip(list) )
    

    Outputs:

    List(23, 24) :: List(a, b) :: List(1.0, 2.0) :: HNil
    

提交回复
热议问题