Skip to content

Add Filter type to Tuple #9235

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 3 commits into from
Jun 29, 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
1 change: 1 addition & 0 deletions compiler/test/dotc/pos-test-pickling.blacklist
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ reference
scala-days-2019-slides
i7048e.scala
i8052.scala
tuple-filter.scala

# Stale symbol: package object scala
seqtype-cycle
Expand Down
18 changes: 18 additions & 0 deletions library/src/scala/Tuple.scala
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,24 @@ object Tuple {
case h *: t => Concat[F[h], FlatMap[t, F]]
}

/** Filters out those members of the tuple for which the predicate `P` returns `false`.
* A predicate `P[X]` is a type that can be either `true` or `false`. For example:
* ```
* type IsString[x] = x match {
* case String => true
* case _ => false
* }
* Filter[(1, "foo", 2, "bar"), IsString] =:= ("foo", "bar")
* ```
*/
type Filter[Tup <: Tuple, P[_] <: Boolean] <: Tuple = Tup match {
case EmptyTuple => EmptyTuple
case h *: t => P[h] match {
case true => h *: Filter[t, P]
case false => Filter[t, P]
}
}

/** 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
10 changes: 10 additions & 0 deletions tests/neg/tuple-filter.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
type P[x] <: Boolean = x match {
case 3 => false
case _ => true
}
type RejectAll[x] = false

def Test =
summon[Tuple.Filter[(1, 2, 3, 4), P] =:= EmptyTuple] // error
summon[Tuple.Filter[(1, 2, 3, 4), RejectAll] =:= (1, 2, 3)] // error
summon[Tuple.Filter[EmptyTuple, P] =:= (1, 2, 3)] // error
10 changes: 10 additions & 0 deletions tests/pos/tuple-filter.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
type P[x] <: Boolean = x match {
case 3 => false
case _ => true
}
type RejectAll[x] = false

def Test =
summon[Tuple.Filter[(1, 2, 3, 4), P] =:= (1, 2, 4)]
summon[Tuple.Filter[(1, 2, 3, 4), RejectAll] =:= EmptyTuple]
summon[Tuple.Filter[EmptyTuple, P] =:= EmptyTuple]