我现在实际上被阻止了大约4个小时。我想要得到一个由int值排序的成对List [String,Int]。功能partiotion工作正常,所以应该bestN,但是当加载到我的解释器时,我得到:找不到类型的证据参数的隐式值Ordered [T]
<console>:15: error: could not find implicit value for evidence parameter of type Ordered[T]
对我的谓词。有人看到问题是什么吗?我此刻真的绝望了......
这是代码:
def partition[T : Ordered](pred: (T)=>Boolean, list:List[T]): Pair[List[T],List[T]] = {
list.foldLeft(Pair(List[T](),List[T]()))((pair,x) => if(pred(x))(pair._1, x::pair._2) else (x::pair._1, pair._2))
}
def bestN[T <% Ordered[T]](list:List[T], n:Int): List[T] = {
list match {
case pivot::other => {
println("pivot: " + pivot)
val (smaller,bigger) = partition(pivot <, list)
val s = smaller.size
println(smaller)
if (s == n) smaller
else if (s+1 == n) pivot::smaller
else if (s < n) bestN(bigger, n-s-1)
else bestN(smaller, n)
}
case Nil => Nil
}
}
class OrderedPair[T, V <% Ordered[V]] (t:T, v:V) extends Pair[T,V](t,v) with Ordered[OrderedPair[T,V]] {
def this(p:Pair[T,V]) = this(p._1, p._2)
override def compare(that:OrderedPair[T,V]) : Int = this._2.compare(that._2)
}
编辑:第一个功能通过应用谓词每个成员把一个表分为二,bestN函数返回一个列表中最低的n个成员列表。和类是有做对的可比性,在这种情况下,我想你做的是:
val z = List(Pair("alfred",1),Pair("peter",4),Pair("Xaver",1),Pair("Ulf",2),Pair("Alfons",6),Pair("Gulliver",3))
这个给定的名单我想例如使用:
bestN(z, 3)
结果:
(("alfred",1), ("Xaver",1), ("Ulf",2))
好了,有了这个代码,我得到一个奇怪的编译错误: '发现:(U,V)' '要求:(U,V)' '高清CMP(A:(U,V) ,b:(U,V))=((a:OrderedPair [U,V])<(b:OrderedPair [U,V]))' – Theolodis
好吧,得到了错误:) – Theolodis