这是合并排序:
def msort[T](less: (T, T) => Boolean)
(xs: List[T]): List[T] = {
def merge(xs: List[T], ys: List[T], acc: List[T]): List[T] =
(xs, ys) match {
case (Nil, _) => ys.reverse ::: acc
case (_, Nil) => xs.reverse ::: acc
case (x :: xs1, y :: ys1) =>
if (less(x, y)) merge(xs1, ys, x :: acc)
else merge(xs, ys1, y :: acc)
}
val n = xs.length / 2
if (n == 0) xs
else {
val (ys, zs) = xs splitAt n
merge(msort(less)(ys), msort(less)(zs), Nil).reverse
}
} //> msort: [T](less: (T, T) => Boolean)(xs: List[T])List[T]
我试图使用以下方法定义元组的比较类型:
val integerSorter = msort[((String, String), Double)]((a._2, b._2) => a._2 < b._2) _
但我收到错误:
<console>:1: error: not a legal formal parameter
val integerSorter = msort[((String, String), Double)]((a._2, b._2) => a._2 < b._2) _
如何定义integerSorter以使其接受((String, String), Double)
类型的元组?
答案 0 :(得分:2)
您需要将定义更改为:
val integerSorter = msort[((String, String), Double)]((a, b) => a._2 < b._2) _