In an earlier question about zipWith
, @Martin Odersky suggested that instead of something like
foo zipWith(_ + _) bar
(where foo
and bar
are Seq
's) that the following is better (and actually works in Scala).
(foo, bar).zipped map (_ + _)
My question is how does map
know that its argument (which superficially would seem to be a pair) should be split into its two elements?
The following actually runs in a worksheet.
val list1 = List(1, 2, 3, 4) //> list1 : List[Int] = List(1, 2, 3, 4)
val list2 = List(5, 6, 7, 8) //> list2 : List[Int] = List(5, 6, 7, 8)
val zippedResult = (list1, list2).zipped //> list3 : scala.runtime.Tuple2Zipped[Int,List[Int],Int,List[Int]] = scala.run
//| time.Tuple2Zipped@f4bf78da
zippedResult.mkString(", ") //> res4: String = (1,5), (2,6), (3,7), (4,8)
zippedResult map (_ + _) //> res5: List[Int] = List(6, 8, 10, 12)
I see that zippedResult
in fact has 4 type parameters and is not just a list of pairs.
val list3 = List((1, 5), (2, 6), (3, 7), (4, 8))
//> list3a : List[(Int, Int)] = List((1,5), (2,6), (3,7), (4,8))
list3 == zippedResult //> res6: Boolean = false
And I can't write
list3 map(_ +_ )
So what is the Tuple2Zipped
type that it can supply two parameters to the map
function? And is zipped
the only way to create instances of it?