List.sum on custom class

后端 未结 3 533
日久生厌
日久生厌 2021-01-15 03:32

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)          


        
3条回答
  •  广开言路
    2021-01-15 04:12

    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
    

    Then you can do:

    println(List(One, One, Zero, One).sum)
    // One
    

提交回复
热议问题