斯卡拉:如何使用foldLeft一个通用的阵列?

斯卡拉:如何使用foldLeft一个通用的阵列?

问题描述:

我有这种方法:

def isSorted[A](as: Array[A], ordered: (A, A) => Boolean): Boolean = {
    val sorted = for (it <- as.sliding(2))
      yield {
        if (it.length == 2) ordered.apply(it(0), it(1))
        else true
      }

    sorted.find(!_).isEmpty
}

我想要做的就是使用 foldLeft 并应用二元运算。然而, foldLeft 需要初始值,我不知道是什么初值我不知道真正的类型 A $ C $提供C>。

What I'd like to do is use foldLeftand apply the binary operator. However, foldLeft requires an initial value and I don't know what initial value I can provide without knowing the real type of A.

我觉得你在做什么,可以简化。

I think what you're doing can be simplified.

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

或者,也许稍微更简明地(但不一定更容易理解):

Or, perhaps a little more concisely (but not necessarily easier to understand):

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)))
}

更新

OK,我想我已经得到了钉简洁的奖金。

OK, I think I've got the concise prize nailed.

def isSorted[A](as: Array[A], ordered: (A, A) => Boolean): Boolean =
  as.isEmpty || as.init.corresponds(as.tail)(ordered)