Skip to content

Commit c457581

Browse files
Add zip on tuples
1 parent 68b0295 commit c457581

File tree

4 files changed

+40
-5
lines changed

4 files changed

+40
-5
lines changed

library/src/scala/Tuple.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ sealed trait Tuple extends Any {
3333
inline def size[This >: this.type <: Tuple]: Size[This] =
3434
DynamicTuple.dynamicSize(this)
3535

36+
inline def zip[This >: this.type <: Tuple, T2 <: Tuple](t2: T2): Zip[This, T2] =
37+
DynamicTuple.dynamicZip(this, t2)
3638
}
3739

3840
object Tuple {
@@ -74,6 +76,12 @@ object Tuple {
7476
case h *: t => F[h] *: Map[t, F]
7577
}
7678

79+
type Zip[T1 <: Tuple, T2 <: Tuple] <: Tuple = (T1, T2) match {
80+
case (h1 *: t1, h2 *: t2) => (h1, h2) *: Zip[t1, t2]
81+
case (Unit, _) => Unit
82+
case (_, Unit) => Unit
83+
}
84+
7785
/** Convert an array into a tuple of unknown arity and types */
7886
def fromArray[T](xs: Array[T]): Tuple = {
7987
val xs2 = xs match {

library/src/scala/runtime/DynamicTuple.scala

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
package scala.runtime
22

3-
import scala.Tuple.Concat
4-
import scala.Tuple.Size
5-
import scala.Tuple.Head
6-
import scala.Tuple.Tail
7-
import scala.Tuple.Elem
3+
import scala.Tuple.{ Concat, Size, Head, Tail, Elem, Zip }
84

95
object DynamicTuple {
106
inline val MaxSpecialized = 22
@@ -253,6 +249,14 @@ object DynamicTuple {
253249
res.asInstanceOf[Result]
254250
}
255251

252+
def dynamicZip[This <: Tuple, T2 <: Tuple](t1: This, t2: T2): Zip[This, T2] = {
253+
if (t1.size == 0 || t2.size == 0) ().asInstanceOf[Zip[This, T2]]
254+
else Tuple.fromArray(
255+
t1.asInstanceOf[Product].productIterator.zip(
256+
t2.asInstanceOf[Product].productIterator).toArray
257+
).asInstanceOf[Zip[This, T2]]
258+
}
259+
256260
def consIterator(head: Any, tail: Tuple): Iterator[Any] =
257261
Iterator.single(head) ++ tail.asInstanceOf[Product].productIterator
258262

tests/run/tuple-ops.check

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
((1,4),(2,5),(3,6))
2+
((1,7),(2,8))
3+
((7,1),(8,2))
4+
()
5+
()

tests/run/tuple-ops.scala

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
val a: (1, 2, 3) = (1, 2, 3)
2+
val b: (4, 5, 6) = (4, 5, 6)
3+
val c: (7, 8) = (7, 8)
4+
val d: Unit = ()
5+
6+
val r1: ((1, 4), (2, 5), (3, 6)) = a.zip(b)
7+
val r2: ((1, 7), (2, 8)) = a.zip(c)
8+
val r3: ((7, 1), (8, 2)) = c.zip(a)
9+
val r4: Unit = d.zip(a)
10+
val r5: Unit = a.zip(d)
11+
12+
@main def Test = List(
13+
r1,
14+
r2,
15+
r3,
16+
r4,
17+
r5)
18+
.foreach(println)

0 commit comments

Comments
 (0)