本文介绍了自定义类上的List.sum的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下表示GF2字段的代码:

I have the following code that represents GF2 field:

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应该扩展某些接口还是我应该实现类型类技术?

And now I'd like to call this function: List(One, One, Zero, One).sum such that GF2._+ would be called for summation, how can I accomplish that? Should GF2 extend some interface or should I implemet type class technique?

推荐答案

您需要隐式数值[GF2]:

You need a Numeric[GF2] implicit:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 20:01