gpt4 book ai didi

generics - scala:如何创建一个通用类型,该通用类型是scala中所有数字类的子类型,以便它可以包含compare方法

转载 作者:行者123 更新时间:2023-12-04 13:45:25 24 4
gpt4 key购买 nike

我正在尝试创建一个泛型类,其泛型类型是Numeric的子类(以确保我正在处理数字。)
我尝试将“class NuVector[T<:Numeric[T])”作为类def并编译良好。

现在,我想向其中添加PartiallyOrdered[T]。所以我做了以下事情:

class NuVector[T<:Numeric[T]) extends PartiallyOrdered[T]
{

/** Array that stores the vector values.
*/
val v = new Array [T] (_length)
/** Range for the storage array.
*/
private val range = 0 to _length - 1

def compare(x:T,y:T)(implicit res:Numeric[T]) :Int=
{
res.compare(x,y)
}

def tryCompareTo [B >: NuVector [T]] (b: B)
(implicit view$1: (B) => PartiallyOrdered [B]): Option [Int] =
{
compare(x,y)
}

implicit def castT2Ordering(x:T):Numeric[T]=x.asInstanceOf[Numeric[T]]
implicit def castB2NuVector [B>:NuVector[T]] (b:B): NuVector[T]=
{
b.asInstanceOf[NuVector[T]]
}

}

它没有编译。
我在编译时遇到的错误是:
 could not find implicit value for parameter res:Numeric[T] 

我正在使用的Scala版本是2.8

任何帮助是极大的赞赏。

谢谢,
〜老虎。
我不知道这是错误还是我的定义有问题。

最佳答案

Scala的Numeric[T]使用"Typeclass Pattern"。说class NuVector[T <: Numeric[T]]并没有任何意义。您想要的是class NuVector[T](implicit n: Numeric[T])

关于generics - scala:如何创建一个通用类型,该通用类型是scala中所有数字类的子类型,以便它可以包含compare方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1357719/

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