Use functional combinators on Scala Tuples?

前端 未结 3 1269
滥情空心
滥情空心 2020-11-30 05:51

\'map\' preserves the number of elements, so using it on a Tuple seems sensible.

My attempts so far:

scala> (3,4).map(_*2)    
error: value map is         


        
3条回答
  •  醉梦人生
    2020-11-30 05:55

    shapeless Supports mapping and folding over tuples via an intermediary HList representation,

    Sample REPL session,

    scala> import shapeless._ ; import Tuples._
    import shapeless._
    import Tuples._
    
    scala> object double extends (Int -> Int) (_*2)
    defined module double
    
    scala> (3, 4).hlisted.map(double).tupled
    res0: (Int, Int) = (6,8)
    

    Where the elements of the tuple are of different types you can map with a polymorphic function with type-specific cases,

    scala> object frob extends Poly1 {
         |   implicit def caseInt     = at[Int](_*2)
         |   implicit def caseString  = at[String]("!"+_+"!")
         |   implicit def caseBoolean = at[Boolean](!_)
         | }
    defined module frob
    
    scala> (23, "foo", false, "bar", 13).hlisted.map(frob).tupled
    res1: (Int, String, Boolean, String, Int) = (46,!foo!,true,!bar!,26)
    

    Update

    As of shapeless 2.0.0-M1 mapping over tuples is supported directly. The above examples now look like this,

    scala> import shapeless._, poly._, syntax.std.tuple._
    import shapeless._
    import poly._
    import syntax.std.tuple._
    
    scala> object double extends (Int -> Int) (_*2)
    defined module double
    
    scala> (3, 4) map double
    res0: (Int, Int) = (6,8)
    
    scala> object frob extends Poly1 {
         |   implicit def caseInt     = at[Int](_*2)
         |   implicit def caseString  = at[String]("!"+_+"!")
         |   implicit def caseBoolean = at[Boolean](!_)
         | }
    defined module frob
    
    scala> (23, "foo", false, "bar", 13) map frob
    res1: (Int, String, Boolean, String, Int) = (46,!foo!,true,!bar!,26)
    

提交回复
热议问题