Can I assume an order on the evaluation of cases of a partial function in Scala?
So for instance, given
protected val eval: PartialFunction[(TestPrimitive, Seq[Literal]), Boolean] = {
case (L3IntLt, Seq(IntLit(x), IntLit(y))) => x < y
case (L3IntLe, Seq(IntLit(x), IntLit(y))) => x <= y
case (L3IntGe, Seq(IntLit(x), IntLit(y))) => x >= y
case (L3IntGt, Seq(IntLit(x), IntLit(y))) => x > y
case (L3Eq, Seq(x, y)) => x == y
case (L3Ne, Seq(x, y)) => x != y
}
If I could assume that cases are evaluated in order I can factor the code as:
protected val eval: PartialFunction[(TestPrimitive, Seq[Literal]), Boolean] = {
case (L3Eq, Seq(x, y)) => x == y
case (L3Ne, Seq(x, y)) => x != y
case (arithp, Seq(IntLit(x), IntLit(y))) => arithp match{
case L3IntLt => x < y
case L3IntLe => x <= y
case L3IntGe => x >= y
case L3IntGt => x > y
}
}
Is it a good programming practice to assume there is an order in the evaluation of the cases?
In Programming in Scala (First Edition), chapter 15, you'll find:
A match expression is evaluated by trying each of the patterns in the order they are written. The first pattern that matches is selected . . .