Giovanni Azua Giovanni Azua - 1 year ago 47
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
. What's the way to do it using functional programming in Scala. I looked for e.g.
but they accumulate rather than visiting every pair of adjacent elements.

Answer Source

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