Showing posts with label sliding. Show all posts
Showing posts with label sliding. Show all posts

Thursday, November 12, 2009

Iterator.Sliding

This topic requires Scala 2.8 or higher.

Iterator and Iterable have most of the most useful methods when dealing with collections. Fold, Map, Filter are probably the most common. But other very useful methods include grouped/groupBy, sliding, find, forall, foreach, and many more. I want to cover Iterator's sliding method.

The def sliding[B >: A](size : Int, step : Int) : GroupedIterator[B] method provides a sliding window on the iterator. The first parameter is the size of the window and the second is the number of elements to skip each time the window is moved. If step == size then this method is the same as grouped. Step defaults to one

Examples:
  1. // notice resulting lists are all 3 long and increases by 1
  2. scala> (1 to 5).iterator.sliding(3).toList
  3. res18: List[Sequence[Int]] = List(List(1, 2, 3), List(2, 3, 4), List(3, 4, 5))
  4. // step is 3 so now there are only 2 groups
  5. scala> (1 to 5).iterator.sliding(4, 3).toList
  6. res19: List[Sequence[Int]] = List(List(1, 2, 3, 4), List(4, 5))
  7. // withPartial(false) makes the partial group be ignored
  8. scala> (1 to 5).iterator.sliding(4, 3).withPartial(false).toList
  9. res21: List[Sequence[Int]] = List(List(1, 2, 3, 4))
  10. scala> val it2 = Iterator.iterate(20)(_ + 5)
  11. it2: Iterator[Int] = non-empty iterator
  12. // withPadding fills in the partial group
  13. // notice with padding is by-name (it is executed each time it is called)
  14. scala> (1 to 5).iterator.sliding(4, 3).withPadding(it2.next).toList
  15. res23: List[Sequence[Int]] = List(List(1, 2, 3, 4), List(4, 5, 20, 25))