Skip to content

Instantly share code, notes, and snippets.

@jsyeo
Created January 19, 2021 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsyeo/a4ba0f82cc2d658339f53c0ff3d84f8b to your computer and use it in GitHub Desktop.
Save jsyeo/a4ba0f82cc2d658339f53c0ff3d84f8b to your computer and use it in GitHub Desktop.
Scala 3 GADTs
object Main {
enum Expr[+T] {
case MyInt(i: Int) extends Expr[Int]
case Bool(b: Boolean) extends Expr[Boolean]
case Add(x: Expr[Int], b: Expr[Int]) extends Expr[Int]
case Eq(x: Expr[T], b: Expr[T]) extends Expr[Boolean]
}
import Expr._
def eval[T](e: Expr[T]): T = {
e match {
case MyInt(i) => i
case Bool(b) => b
case Add(x, y) => eval(x) + eval(y)
case Eq(x, y) => eval(x) == eval(y)
}
}
def main(args: Array[String]): Unit = {
println(eval(Add(MyInt(1), MyInt(2))))
println(eval(Add(Bool(true), MyInt(2)))) // Fails at compile time
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment