我有一个数组val x : Array[Double],想检查作为x(i) <= x(i+1)所有功能的前提i。使用Scala中的函数式编程实现此目的的方式是什么。我寻找例如foldLeft或foldRight但它们积累而不是访问每一对相邻元素。
考虑一下:
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)
| 归档时间: |
|
| 查看次数: |
343 次 |
| 最近记录: |