gpt4 book ai didi

scala - 如何对自定义类型列表使用 sum?

转载 作者:行者123 更新时间:2023-12-04 06:24:28 26 4
gpt4 key购买 nike

引用下面的代码片段:

class Foo(val b:BigDecimal) {
def +(f:Foo) = new Foo(b+f.b)
}
val l = List(new Foo(1), new Foo(2))

l.sum // gives error: could not find implicit value for parameter num: Numeric[Foo]

让它发挥作用的最简单方法是什么?我知道我必须定义一些隐式转换。

注意:类 Foo 位于库内,因此我无法编辑该代码。我需要在 Foo 之外执行此操作。

尽管有几个使用Numeric类型的示例,但我找不到这个特殊情况的答案

最佳答案

您可以定义必要的隐式:

  class Foo(val b:BigDecimal) {
def +(f:Foo) = new Foo(b+f.b)
}
object Foo {
implicit val numericFoo: Numeric[Foo] = new Numeric[Foo] {
override def plus(x: Foo, y: Foo): Foo = new Foo(x.b + y.b)
override def minus(x: Foo, y: Foo): Foo = new Foo(x.b - y.b)
override def times(x: Foo, y: Foo): Foo = new Foo(x.b * y.b)
override def negate(x: Foo): Foo = new Foo(-x.b)
override def fromInt(x: Int): Foo = new Foo(x)
override def toInt(x: Foo): Int = x.b.toInt
override def toLong(x: Foo): Long = x.b.toLong
override def toFloat(x: Foo): Float = x.b.toFloat
override def toDouble(x: Foo): Double = x.b.toDouble
override def compare(x: Foo, y: Foo): Int = x.b.compare(y.b)
}
}

或者只是

implicit val numericFoo: Numeric[Foo] = new Numeric[Foo] {
override def plus(x: Foo, y: Foo): Foo = x + y
override def minus(x: Foo, y: Foo): Foo = ???
override def times(x: Foo, y: Foo): Foo = ???
override def negate(x: Foo): Foo = ???
override def fromInt(x: Int): Foo = new Foo(x)
override def toInt(x: Foo): Int = ???
override def toLong(x: Foo): Long = ???
override def toFloat(x: Foo): Float = ???
override def toDouble(x: Foo): Double = ???
override def compare(x: Foo, y: Foo): Int = ???
}

或者您可以定义自己的扩展方法

  implicit class FooList(foos: List[Foo]) {
def sum1: Foo = foos.foldLeft(new Foo(0))(_ + _)
}

l.sum1

关于scala - 如何对自定义类型列表使用 sum?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47314416/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com