Canonical ways to do this in a for loop:
scala> val xs = List(1,2,3,4,3,2) xs: List[Int] = List(1, 2, 3, 4, 3, 2) scala> for (List(left,right) <- xs.sliding(2) if (left < right)) println(left + " < " + right) 1 < 2 2 < 3 3 < 4 scala> for ((left,right) <- (xs zip xs.tail) if (left < right)) println(left + " < " + right) 1 < 2 2 < 3 3 < 4
(By the way, you are probably better off putting the if statement outside, rather than inside, for understanding in this example.)
If you have indexes instead of values, you simply search for them using the same template. Personally, I do not think this template is very clear or useful. It is slow, has weird angular scales with lists that aren't filled out, and it's hard to keep track of what's happening. Instead, I define
class PairedIterable[A](it: Iterable[A]) { def foreachpair(f: (A,A) => Unit) = { val i = it.iterator if (i.hasNext) { var prev = i.next while (!ans && i.hasNext) { val x = i.next f(prev,x) prev = x } } } } implicit def iterable_has_pairs[A](it: Iterable[A]) = new PairedIterable(it)
which can then be used as follows:
scala> xs.foreachpair((left, right) => if (left < right) println(left + " < " + right)) 1 < 2 2 < 3 3 < 4
The options forallpair, existpair, and findpair are especially useful.
Rex kerr
source share