我有以下代表 GF2 字段的代码:
trait GF2 {
def unary_- = this
def + (that: GF2): GF2
def * (that: GF2): GF2
def / (that: GF2) = that match {
case Zero => throw new IllegalArgumentException("Div by 0")
case _ => this
}
}
object Zero extends GF2 {
override def toString = "Zero"
def + (that: GF2) = that
def * (that: GF2) = this
}
object One extends GF2 {
override def toString = "One"
def + (that: GF2) = that match { case One => Zero ; case _ => this }
def * (that: GF2) = that match { case One => this ; case _ => that }
}
现在我想调用这个函数:List(One, One, Zero, One).sum
这样 GF2._+
就会被调用总结,我怎样才能做到这一点? GF2
应该扩展一些接口(interface)还是应该实现类型类技术?
最佳答案
你需要一个 Numeric[GF2] 隐式:
trait GF2IsNumeric extends Numeric[GF2] {
def plus(x: GF2, y: GF2): GF2 = x + y
def minus(x: GF2, y: GF2): GF2 = x + (-y)
def times(x: GF2, y: GF2): GF2 = x * y
def negate(x: GF2): GF2 = -x
def fromInt(x: Int): GF2 = ???
def toInt(x: GF2): Int = ???
def toLong(x: GF2): Long = ???
def toFloat(x: GF2): Float = ???
def toDouble(x: GF2): Double = ???
override def zero = Zero
override def one = One
}
trait GF2Ordering extends scala.math.Ordering[GF2] {
override def compare(a: GF2, b: GF2) = if (a == b) 0 else if (b == One) 1 else -1
}
implicit object GF2IsNumeric extends GF2IsNumeric with GF2Ordering
然后你可以这样做:
println(List(One, One, Zero, One).sum)
// One
关于List.sum 自定义类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21787505/