我剛剛開始使用 Scala,我正在嘗試創建一種資料型別,它是整數和特殊值 Infinity 和 -Infinity 的聯合。我試圖弄清楚如何在 Scala 中以最慣用的方式做到這一點。
到目前為止,我嘗試過的一種選擇是使用特征:
trait MySet
case object Infinity extends MySet
case object NegInfinity extends MySet
case class Value(value: Int) extends MySet
這接縫作業,但我不確定這是否是最聰明的做法。最后,我想用它來建模代數結構,如群、幺半群等,以 MySet 作為載體集。例如做這樣的事情:
trait Monoid[T]:
val zero: T
def @ (x: T, y: T): T
那個方向的東西。
感謝您的所有建議!
uj5u.com熱心網友回復:
正如 Luis 在評論中所說的那樣, maketrait sealed將使編譯器知道什么是可能的擴展MySet
否則,您的幺半群可以通過以下操作來豐富:
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)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/338802.html
標籤:斯卡拉
