Created
January 28, 2022 09:51
-
-
Save bishabosha/90f9f6dc76fe69fa949904b722e018a7 to your computer and use it in GitHub Desktop.
Statically get the ordinal of any child of a sum-type in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.compiletime.ops.int.S | |
import scala.compiletime.constValue | |
import scala.deriving.Mirror | |
object Tuples { | |
type IndexOf[Q, T <: Tuple, I <: Int] <: Int = T match { | |
case EmptyTuple => -1 | |
case Q *: ts => I | |
case _ *: ts => IndexOf[Q, ts, S[I]] | |
} | |
} | |
object Sums { | |
inline def ordinalOf[C <: S, S](using m: Mirror.SumOf[S]): Int = { | |
type Index = Tuples.IndexOf[C, m.MirroredElemTypes, 0] | |
constValue[Index] | |
} | |
} | |
enum Foo { | |
case A | |
case B | |
case C | |
} | |
@main def Test = | |
inline def fooOrd[T <: Foo] = Sums.ordinalOf[T, Foo] | |
assert(fooOrd[Foo.A.type] == 0) | |
assert(fooOrd[Foo.B.type] == 1) | |
assert(fooOrd[Foo.C.type] == 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment