Skip to content

Commit 6280e71

Browse files
KacperFKorbandwijnand
authored andcommitted
Implement Tuple.FlatMap
closes #13163
1 parent 609a576 commit 6280e71

File tree

4 files changed

+34
-0
lines changed

4 files changed

+34
-0
lines changed

library/src/scala/Tuple.scala

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ sealed trait Tuple extends Product {
5454
inline def map[F[_]](f: [t] => t => F[t]): Map[this.type, F] =
5555
runtime.Tuples.map(this, f).asInstanceOf[Map[this.type, F]]
5656

57+
/** Called on a tuple `(a1, ..., an)`, returns a new tuple `f(a1) ++ ... ++ f(an)`.
58+
* The result is typed as `Concat[F[A1], ...Concat[F[An], EmptyTuple]...])` if the tuple type is fully known.
59+
*/
60+
inline def flatMap[F[_] <: Tuple](f: [t] => t => F[t]): FlatMap[this.type, F] =
61+
runtime.Tuples.flatMap(this, f).asInstanceOf[FlatMap[this.type, F]]
62+
5763
/** Given a tuple `(a1, ..., am)`, returns the tuple `(a1, ..., an)` consisting
5864
* of its first n elements.
5965
*/

library/src/scala/runtime/Tuples.scala

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,11 @@ object Tuples {
388388
case _ => fromIArray(self.productIterator.map(f(_).asInstanceOf[Object]).toArray.asInstanceOf[IArray[Object]]) // TODO use toIArray
389389
}
390390

391+
def flatMap[F[_] <: Tuple](self: Tuple, f: [t] => t => F[t]): Tuple = self match {
392+
case EmptyTuple => self
393+
case _ => fromIArray(self.toIArray.flatMap(f(_).toIArray))
394+
}
395+
391396
def take(self: Tuple, n: Int): Tuple = {
392397
if (n < 0) throw new IndexOutOfBoundsException(n.toString)
393398
val selfSize: Int = self.size

tests/run/TupleFlatMap.check

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
()
2+
(1,1,2,2,x,x,d,d)
3+
()
4+
(1,1!,x,x!)

tests/run/TupleFlatMap.scala

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
@main def Test = {
2+
3+
println(
4+
Tuple().flatMap[[t] =>> (t, t)]([t] => (x: t) => (x, x))
5+
)
6+
7+
println(
8+
(1, 2, "x", "d").flatMap[[t] =>> (t, t)]([t] => (x: t) => (x, x))
9+
)
10+
11+
println(
12+
(1, "x").flatMap[[t] =>> EmptyTuple]([t] => (x: t) => Tuple())
13+
)
14+
15+
println(
16+
(1, "x").flatMap[[t] =>> (t, String)]([t] => (x: t) => (x, x.toString + "!"))
17+
)
18+
19+
}

0 commit comments

Comments
 (0)