List.sum 自定义类

标签 list scala types sum

我有以下代表 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/

相关文章:

scala - 在类中使用隐式对象

java - Scala 和 Eclipse : Export as Jar File, 但找不到 main 方法

c - 我怎样才能纠正我的c代码?

java - Maven 自定义依赖类型

java - 使用 Orika 在包含列表的两个对象之间进行映射

javascript - Material 用户界面 : how to change fontSize in Lists?

python - 打印出文本文件中的句子数

list - 等效代码,一个有效,另一个无效

scala - 使用 Actors 时在哪里定义案例类

linux - 在系统范围内更改游标类型