[英]Order of evaluation of cases in Scala partial function
Can I assume an order on the evaluation of cases of a partial function in Scala? 我可以对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: 在Scala编程 (第一版)的第15章中 ,您将找到:
A match expression is evaluated by trying each of the patterns in the order they are written. 通过按书写顺序尝试每种模式来评估匹配表达式。 The first pattern that matches is selected . 选择第一个匹配的模式。 . 。 . 。
Yes, cases are evaluated top to bottom, first one to match wins. 是的,案例从上到下进行评估,第一个与获胜者匹配。 It is a fine practice as it is generally understood by scala programmers, and it's a very common pattern used by a lot of scala code. Scala程序员通常会理解这是一种很好的做法,这是许多Scala代码使用的非常常见的模式。
For example, for non-exhaustive matches, it is common to specify a catch all: 例如,对于非穷举匹配,通常指定全部捕获:
x match {
case "value1" => ...
case "value2" => ...
case other => ...
}
Clearly this is dependent on order, since if the catch-all case was at the beginning, it would catch everything. 显然,这取决于顺序,因为如果包罗万象的案件是在开始时,它将抓住一切。
假定评估顺序是我们无论如何都需要做的事情之一。此外,我将像您一样重构我的代码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.