3 ms·
How is this not pattern matching? In Scala, I would write: enum Expr: case INT(value: Int) case ADD(left: Expr, right: Expr) case MULT(left, Exp
by gavinray 4y ago
How is this not pattern matching?
In Scala, I would write:
enum Expr:
case INT(value: Int)
case ADD(left: Expr, right: Expr)
case MULT(left, Expr, right: Expr)
def eval(e: Expr): Int = e match
case INT(value) => value
case ADD(l, r) => eval(l) + eval(r)
case MULT(l, r) => eval(l) + eval(r)
This "match" syntax is the example given in the Scala docs for Pattern Matching:
https://docs.scala-lang.org/tour/pattern-matching.html https://docs.scala-lang.org/tour/pattern-matching.html
The fact that Java happens to use "switch" instead of "match" is one of syntax, not semantics.
JDK 17/18 introduces Sealed Types, which allow you to create ADT's
sealed interface Expr {
record INT(Integer value) implements Expr {}
record ADD(Expr l, Expr r) implements Expr {}
// etc
}
When you "switch" over sealed types, the switch expression is exhaustive if all members have branches and requires no default case + is typesound.
- javcasas 4y agoCan you pattern match deeply? Can you make a case for ADD where the first param is a MULT with the second param of the MULT being INT(5)?
- kaba0 4y agoIt is underway (destructors are not yet finalized).
- dunefox 4y agoDoes it support matching patterns in data structures? f [ [1, _]. [3, _] ] = ... f [ [], [10, 20] ] = ...
- kaba0 4y agoGiven that java doesn’t have too much syntax sugar for data structures, I doubt this will come, but other kinds of destructors will be possible.