在Scala中,检查数组是否单调的有效方法是什么?

Sky*_*ker 4 scala

我有一个数组val x : Array[Double],想检查作为x(i) <= x(i+1)所有功能的前提i。使用Scala中的函数式编程实现此目的的方式是什么。我寻找例如foldLeftfoldRight但它们积累而不是访问每一对相邻元素。

Nya*_*vro 5

考虑一下:

def isMonotonic(arr:Array[Int]) = 
   if (arr.isEmpty) true
   else (arr, arr.tail).zipped.forall {case (a,b) => a <= b}
Run Code Online (Sandbox Code Playgroud)

简化的解决方案(感谢@ som-snytt):

def isMonotonic(arr:Array[Int]) = 
   (arr, arr.drop(1)).zipped.forall (_ <= _)
Run Code Online (Sandbox Code Playgroud)

  • 避免中间集合:((vs,vs.view.drop(1))。zip.forall(_ &lt;_)`。 (2认同)