Sum types are amazing! Once I got introduced to them in Rust, it was hard to go back to languages like Java where the enum type is pitiful in comparison.
int eval(Expr e) {
return switch (e) {
case ConstantExpr(var i) -> i;
case PlusExpr(var a, var b) -> eval(a) + eval(b);
case TimesExpr(var a, var b) -> eval(a) \* eval(b);
case NegExpr(var e) -> -eval(e);
// no default needed, Expr is sealed
}
}
But it only got that recently.Sometimes I wonder: will they become table stakes in the future, or will we wake up to their (currently unknown) downsides in a decade or two? Think of how exceptions are now considered a poor pattern, compared to errors as values.