List.sum on custom class

后端 未结 3 534
日久生厌
日久生厌 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:28

    Look at the signature of sum:

    def sum[B >: A](implicit num: Numeric[B]): B
    

    I was about to suggest that you make GF2 a member of Numeric typeclass by providing and implicit value of type Numeric[GF2], but then I looked at the definition of Numeric and realized that it contains a ton of operations completely irrelevant to summation that you would have to implement.

    I don't like this, I think sum method should require some more abstract typeclass (a monoid, perhaps?).

    So, I think your best option (unless you want to implement entire Numeric instance) is to use either reduce (will work only with non-empty lists) or fold:

    yourList.reduce(_ + _)
    yourList.fold(Zero)(_ + _)
    

提交回复
热议问题