如何在Scala中表示包含+- Infinity的整数集合



我刚刚开始使用Scala,我正在尝试创建一个数据类型,它是整数和特殊值+Infinity和-Infinity的并集。我正在尝试用Scala中最习惯的方式来实现这个。

到目前为止,我尝试过的一个选择是使用trait:

trait MySet
case object Infinity extends MySet 
case object NegInfinity extends MySet 
case class Value(value: Int) extends MySet 

这似乎可行,但我不确定这是否是最聪明的方法。最后,我想用MySet作为载体集来建模代数结构,如群、Monoids等。例如:

trait Monoid[T]:
val zero: T
def @+(x: T, y: T): T

在那个方向。

谢谢你的建议!

就像Luis在评论中说的,让trait,sealed,这样编译器就会知道什么是MySet的可能扩展

否则,您的monoid可以通过以下操作进行充实:

val mySetMonoid = new Monoid[MySet] {
// 1) first the associative operation, which I guess would be +
def op(a1: MySet, a2: MySet) = (a1, a2) match {
case (Value(x), Value(y)) => x+y
case (Value(_), Infinity) => Infinity
case (Value(_), NegInfinity) => NegInfinity
case (Infinity, Value(_)) => Infinity
case (NegInfinity, Value(_)) => NegInfinity
case (NegInfinity, Infinity) => throw new UnsupportedOperationException(..) 
// here you need to be more specific
// on how you want to handle +infinity 
// and -infinity being added
}
// 2) then the definition of your zero in regard of the associative operation
val zero = Value(0)
}

最新更新