Skip to content

Add Tuple match types #9217

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions library/src/scala/Tuple.scala
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,23 @@ object Tuple {
case x *: xs => S[Size[xs]]
}

/** Fold a tuple `(T1, ..., Tn)` into `F[T1, F[... F[Tn, Z]...]]]` */
type Fold[T <: Tuple, Z, F[_, _]] = T match
case EmptyTuple => Z
case h *: t => F[h, Fold[t, Z, F]]

/** Converts a tuple `(T1, ..., Tn)` to `(F[T1], ..., F[Tn])` */
type Map[Tup <: Tuple, F[_]] <: Tuple = Tup match {
case EmptyTuple => EmptyTuple
case h *: t => F[h] *: Map[t, F]
}

/** Converts a tuple `(T1, ..., Tn)` to a flattened `(..F[T1], ..., ..F[Tn])` */
type FlatMap[Tup <: Tuple, F[_] <: Tuple] <: Tuple = Tup match {
case EmptyTuple => EmptyTuple
case h *: t => Concat[F[h], FlatMap[t, F]]
}

/** Given two tuples, `A1 *: ... *: An * At` and `B1 *: ... *: Bn *: Bt`
* where at least one of `At` or `Bt` is `EmptyTuple` or `Tuple`,
* returns the tuple type `(A1, B1) *: ... *: (An, Bn) *: Ct`
Expand Down
14 changes: 14 additions & 0 deletions tests/pos/tuple-flatmap.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@

type Empty[X] = EmptyTuple
type Twice[X] = (X, X)

def test =
val a1: EmptyTuple = ??? : Tuple.FlatMap[EmptyTuple, Empty]
val a2: EmptyTuple = ??? : Tuple.FlatMap[(Int, String), Empty]

val b1: EmptyTuple = ??? : Tuple.FlatMap[EmptyTuple, Tuple1]
val b2: (Int, String) = ??? : Tuple.FlatMap[(Int, String), Tuple1]

val c1: EmptyTuple = ??? : Tuple.FlatMap[EmptyTuple, Twice]
val c2: (Int, Int, String, String) = ??? : Tuple.FlatMap[(Int, String), Twice]
val c3: (Int, List[Int], String, List[String]) = ??? : Tuple.FlatMap[(Int, String), [X] =>> (X, List[X])]
8 changes: 8 additions & 0 deletions tests/pos/tuple-fold.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

type Empty[X] = EmptyTuple
type Twice[X] = (X, X)

def test =
val a1: EmptyTuple = ??? : Tuple.Fold[EmptyTuple, Nothing, Tuple2]
val a2: (Int, (String, Nothing)) = ??? : Tuple.Fold[(Int, String), Nothing, Tuple2]
val a3: Int | String | Char = ??? : Tuple.Fold[(Int, String, Char), Nothing, [X, Y] =>> X | Y]