Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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.

like image 920
SkyWalker Avatar asked Dec 19 '22 13:12

SkyWalker


2 Answers

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 (_ <= _)
like image 52
Nyavro Avatar answered Feb 09 '23 01:02

Nyavro


You can use IterableLike.sliding:

val isMonotonic = 
  Seq(1,2,3,4,5).sliding(2).forall {
    case Seq(x, y) => x < y
    case _ => true
  }

Edit:

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
  }
like image 45
Yuval Itzchakov Avatar answered Feb 09 '23 01:02

Yuval Itzchakov