上一节课的排序函数不够通用,类型只适用Int:
object mergesort{
def msort(xs: List[Int]):List[Int] = {
val n = xs.length/2
if(n==0) xs
else{
def merge(xs:List[Int],ys: List[Int]):List[Int] = (xs,ys)match {
case (Nil,ys) => ys
case (xs,Nil) => xs
case (x::xs1,y::ys1) =>
if(x<y) x::merge(xs1,ys1)
else y::merge(xs,ys1)
}
val (fst,snd) = xs splitAt n
merge(msort(fst),msort(snd))
}
}
val nums = List(2,-4,5,7,1)
msort(nums)
}
object mergesort{
def msort[T](xs: List[T])(lt:(T,T) => Boolean):List[T] = { val n = xs.length/2 if(n==0) xs else{ def merge(xs:List[T],ys: List[T]):List[T] = (xs,ys)match { case (Nil,ys) => ys
case (xs,Nil) => xs
case (x::xs1,y::ys1) =>
if(lt(x,y)) x::merge(xs1,ys1)
else y::merge(xs,ys1)
}
val (fst,snd) = xs splitAt n
merge(msort(fst)(lt),msort(snd)(lt))
}
}
val nums = List(2,-4,5,7,1)
msort(nums)((x:Int,y:Int) => x < y) val fruits = List("apple","pineapple","orange") msort(fruits)((x: String,y:String) =>x.compareTo(y)<0) }
在函数的参数中使用 编译器会根据类型得到正确的隐含参数
对排序函数再改造一下,scala提供了常用的比较操作Ordering,在scala.math包下:
object mergesort{
def msort[T](xs: List[T])(ord:Ordering)):List[T] = {
val n = xs.length/2
if(n==0) xs
else{
def merge(xs:List[T],ys: List[T]):List[T] = (xs,ys)match {
case (Nil,ys) => ys
case (xs,Nil) => xs
case (x::xs1,y::ys1) =>
if(ord.lt(x,y)) x::merge(xs1,ys1)
else y::merge(xs,ys1)
}
val (fst,snd) = xs splitAt n
merge(msort(fst)(ord),msort(snd)(ord))
}
}
val nums = List(2,-4,5,7,1)
msort(nums)(Ordering.Int)
val fruits = List("apple","pineapple","orange")
msort(fruits)(Ordering.String)
}
利用implicit,我们可以省去一些参数。scala编译器会帮我们匹配类型:
def msort[T](xs: List[T])(implicit ord:Ordering)):List[T] = {
...
}
调用时只需:
msort(List(1,2,3)) 或者msort(List("1","2","3"))
编译器如何查找implicit定义:
以上的原则 Ordering是包含类型参数的 完整的形式是 Ordering[T]
所以编译器在使用 List(1,2,3) 时会正确找到 Ordering[Int]
而为 List("1","2","3") 时则为Ordering[String]
如:
def less[T](a:T,b:T)(implicit ord:math.Ordering[T]):Boolean=ord.lt(a, b) less(1,2)