gpt4 book ai didi

generics - 如何使用值编写代码[T : Numeric] more “flexible” like the “unboxed” counterparts?

转载 作者:行者123 更新时间:2023-12-03 06:22:43 26 4
gpt4 key购买 nike

如果我有像 5 * 5.0 这样的代码,结果将转换为最准确的类型,Double

但这似乎不适用于这样的代码

case class Value[T : Numeric](value: T) {
type This = Value[T]
def +(m: This) = Value[T](implicitly[Numeric[T]].plus(value, m.value))
...
}

implicit def numToValue[T : Numeric](v: T) = Value[T](v)

有没有办法让someIntValue + double这样的东西工作,其中someIntValueValue[Int]doubleDouble

PS:很抱歉这个标题远不完美。我感谢您提出更好措辞的建议......

最佳答案

您可以通过创建隐式运算符来做到这一点(需要大量的工作):

abstract class Arith[A,B,C] {
def +(a: A, b: B): C
def -(a: A, b: B): C
def *(a: A, b: B): C
def /(a: A, b: B): C
}
implicit object ArithIntLong extends Arith[Int,Long,Long] {
def +(a: Int, b: Long) = a+b
def -(a: Int, b: Long) = a-b
def *(a: Int, b: Long) = a*b
def /(a: Int, b: Long) = a/b
}
...
def f[A,B,C](a: A, b: B)(implicit arith: Arith[A,B,C]) = arith.*(a,b)


scala> f(5,10L)
res46: Long = 50

但你确实需要做的比这更多,因为你需要 A 和 B 单独的数字等价物,并且需要以两种方式定义非对称操作。鉴于涉及三种类型,专门化并不实际。

关于generics - 如何使用值编写代码[T : Numeric] more “flexible” like the “unboxed” counterparts?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7630486/

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