Hacker News new | past | comments | ask | show | jobs | submit login

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

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.



Can 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)?


It is underway (destructors are not yet finalized).


Does it support matching patterns in data structures?

    f [ [1, _]. [3, _] ] = ...

    f [ [], [10, 20] ] = ...


Given 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.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: