Avn*_*arr 6 enumeration scala traits comparable partial-ordering
我有一个由某种“状态机”(“流程图”)定义的分布式系统
每个系统都将状态写入共享“日志”中
我将每个州表示为密封特征的一部分以及该州的给定“状态”
我想“合并/减少”到代表当前进度的单一状态。
(有一些放宽措施,因为并非所有项目都必须成功才能成功完成最终状态)
有 2 个密封特征代表流程:
sealed trait System
case object A extends System
case object B extends System
case object C extends System
...
sealed trait Status
case object Pending extends Status
case object InProgress extends Status
case object Success extends Status
case object Fail extends Status
Run Code Online (Sandbox Code Playgroud)
日志:
A, Success
B, Fail
C, Pending
...
...
Run Code Online (Sandbox Code Playgroud)
现在我用一组规则来定义单个状态降低
基本上它优先
A < B < C, ... < Z
和
Pending < InProgress < Success < Fail
因此,如果存在以下状态:
(A, Success)相对(C, Pending)
我想把它减少到(C,Pending)
而如果
(A,Success)相对(B, Fail)
我想把它减少到(B, Fail)
在我的例子中,我可以将其建模为简单的整数比较(可能使用我明确测试的异常值)
我不清楚如何使密封特征具有可比性/可排序性,这将使我的生活变得更轻松
沿着这些思路就足够了:
def reduce(states: Seq[(System,Status)]) : (System,Status) = {
states.order... {left.system < right.system) && (a.status < b.status) ... possibly another ordering test ....}.tail // take the last one in the ordering
}
Run Code Online (Sandbox Code Playgroud)
您可以定义一个scala.math.Ordering[Status]:
object StatusOrdering extends Ordering[Status] {
def compare(x: Status, y: Status): Int =
(x, y) match {
// assuming that the ordering is Pending < InProgress < Success < Fail...
case (_, _) if (x eq y) => 0
case (Pending, _) => -1
case (_, Pending) => 1
case (InProgress, _) => -1
case (_, InProgress) => 1
case (Success, _) => -1
case (_, Success) => 1
case _ => 0 // (Fail, Fail)
}
Run Code Online (Sandbox Code Playgroud)
在你的 中reduce,你可以
import StatusOrdering.mkOrderingOps
Run Code Online (Sandbox Code Playgroud)
有了朋友,你的Status物品就会变得更加丰富。<
也可以使用trait扩展Ordered[Status],它定义了特征中的规范排序:
sealed trait OrderedStatus extends Ordered[OrderedStatus] {
def compare(that: OrderedStatus): Int =
(this, that) match {
case (x, y) if (x eq y) => 0
case (Qux, _) => -1
case (_, Qux) => 1
case (Quux, _) => -1
case (_, Quux) => 1
case _ => 0
}
}
case object Qux extends OrderedStatus
case object Quux extends OrderedStatus
case object Quuux extends OrderedStatus
Run Code Online (Sandbox Code Playgroud)
那么你不必 import ,但我个人不喜欢在方法中mkOrderingOps向前使用扩展(并且在每种情况下使用样板对象的替代方案更糟糕)。case objectscomparecompare
| 归档时间: |
|
| 查看次数: |
1267 次 |
| 最近记录: |