I would like to refactor this piece of Scala code in functional style:
var k = -1
for (i <- 0 until array.length)
if ((i < array.length - 1) && array(i) < array(i + 1))
k = i
Array in Scala has indexWhere, which can be used for something like val index = array.indexWhere(c => c == 'a'). I’m looking for something similar, which would take into account two sequential elements of array.
When you need to look at adjacent elements in a collection, the usual functional approach is to “zip” the collection with its tail. Consider the following simplified example:
Now we can use
indexWhere:In your case, the following is essentially equivalent to your code:
I’m using
lastIndexWhereinstead ofindexWhere, since in your code you don’t stop the loop when you hit a pair for which the predicate holds.