Use functional combinators on Scala Tuples?

前端 未结 3 1270
滥情空心
滥情空心 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 06:00

    In general, the element types of a tuple aren't the same, so map doesn't make sense. You can define a function to handle the special case, though:

    scala> def map[A, B](as: (A, A))(f: A => B) = 
         as match { case (a1, a2) => (f(a1), f(a2)) } 
    map: [A,B](as: (A, A))(f: (A) => B)(B, B)
    
    scala> val p = (1, 2)    
    p: (Int, Int) = (1,2)
    
    scala> map(p){ _ * 2 }
    res1: (Int, Int) = (2,4)
    

    You could use the Pimp My Library pattern to call this as p.map(_ * 2).

    UPDATE

    Even when the types of the elements are not the same, Tuple2[A, B] is a Bifunctor, which can be mapped with the bimap operation.

    scala> import scalaz._
    import scalaz._
    
    scala> import Scalaz._
    import Scalaz._
    
    scala> val f = (_: Int) * 2
    f: (Int) => Int = 
    
    scala> val g = (_: String) * 2
    g: (String) => String = 
    
    scala> f <-: (1, "1") :-> g
    res12: (Int, String) = (2,11)
    

    UPDATE 2

    http://gist.github.com/454818

提交回复
热议问题