Created
January 19, 2021 08:01
-
-
Save jsyeo/a4ba0f82cc2d658339f53c0ff3d84f8b to your computer and use it in GitHub Desktop.
Scala 3 GADTs
This file contains 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
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