I have an array val x : Array[Double]
and would like to check as precondition to a function that every x(i) <= x(i+1)
for all i
. What's the way to do it using functional programming in Scala. I looked for e.g. foldLeft
or foldRight
but they accumulate rather than visiting every pair of adjacent elements.
Consider this:
def isMonotonic(arr:Array[Int]) =
if (arr.isEmpty) true
else (arr, arr.tail).zipped.forall {case (a,b) => a <= b}
Simplified solution (thanks to @som-snytt):
def isMonotonic(arr:Array[Int]) =
(arr, arr.drop(1)).zipped.forall (_ <= _)
You can use IterableLike.sliding
:
val isMonotonic =
Seq(1,2,3,4,5).sliding(2).forall {
case Seq(x, y) => x < y
case _ => true
}
Since you're using an Array[Double]
, you'll need:
val isMonotonic =
Array(1d, 2d, 3d, 4d, 5d).sliding(2).forall {
case Array(x, y) => x < y
case _ => true
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With