Giovanni Azua Giovanni Azua - 3 months ago 6
Scala Question

In Scala what's a functional way to check that an array is monotonic?

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.

Answer

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 (_ <= _)