我认为您正在做的事情可以简化。
def isSorted[A](as: Array[A], ordered: (A, A) => Boolean): Boolean = {
if (as.size < 2)
true
else
as.sliding(2).find(x => !ordered(x(0),x(1))).isEmpty
}
isSorted: [A](as: Array[A], ordered: (A, A) => Boolean)Boolean
scala> isSorted( Array(2), {(a:Int,b:Int) => a < b} )
res42: Boolean = true
scala> isSorted( Array(2,4), {(a:Int,b:Int) => a < b} )
res43: Boolean = true
scala> isSorted( Array(2,4,5), {(a:Int,b:Int) => a < b} )
res44: Boolean = true
scala> isSorted( Array(2,14,5), {(a:Int,b:Int) => a < b} )
res45: Boolean = false
或者,也许更简洁一点(但不一定更容易理解):
def isSorted[A](as: Array[A], ordered: (A, A) => Boolean): Boolean = {
if (as.size < 2)
true
else
!as.sliding(2).exists(x => ordered(x(1),x(0)))
}
更新
好的,我想我已经确定了简明奖。
def isSorted[A](as: Array[A], ordered: (A, A) => Boolean): Boolean =
as.isEmpty || as.init.corresponds(as.tail)(ordered)