Functional code for finding index in array

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.

Answers


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:

scala> val xs = List(5, 4, 2, 3, 1)
xs: List[Int] = List(5, 4, 2, 3, 1)

scala> val tail = xs.tail
tail: List[Int] = List(4, 2, 3, 1)

scala> xs.zip(tail)
res0: List[(Int, Int)] = List((5,4), (4,2), (2,3), (3,1)

Now we can use indexWhere:

scala> res0.indexWhere { case (x, y) => x < y }
res1: Int = 2

In your case, the following is essentially equivalent to your code:

val k = (array zip array.tail) lastIndexWhere { case (x, y) => x < y }

I'm using lastIndexWhere instead of indexWhere, since in your code you don't stop the loop when you hit a pair for which the predicate holds.


Need Your Help

What is a better design if two subclasses have the same method?

oop

Just as an example, if House is the base class, and Colonial is a subclass of House, and Colonial has a method that is goUpstairs. There is another class called Mansion which is also a subclass of

Duplicate Control ID's leading to a exception

c# asp.net caching sitecore

I recently released some code to our production website and I noticed that IIS was logging some errors with the exception text of:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.