Scala: sliding(N,N) vs grouped(N)

The reason to use sliding instead of grouped is really only applicable when you want to have the ‘windows’ be of a length different than what you ‘slide’ by (that is to say, using sliding(m, n) where m != n):

listToGroup.sliding(2,3).toList
//returns List(List(1, 2), List(4, 5), List(7, 8))

listToGroup.sliding(4,3).toList
//returns List(List(1, 2, 3, 4), List(4, 5, 6, 7), List(7, 8))

As som-snytt points out in a comment, there’s not going to be any performance difference, as both of them are implemented within Iterator as returning a new GroupedIterator. However, it’s simpler to write grouped(n) than sliding(n, n), and your code will be cleaner and more obvious in its intended behavior, so I would recommend grouped(n).

As an example for where to use sliding, consider this problem where grouped simply doesn’t suffice:

Given a list of numbers, find the sublist of length 4 with the greatest sum.

Now, putting aside the fact that a dynamic programming approach can produce a more efficient result, this can be solved as:

def maxLengthFourSublist(list: List[Int]): List[Int] = {
    list.sliding(4,1).maxBy(_.sum)
}

If you were to use grouped here, you wouldn’t get all the sublists, so sliding is more appropriate.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)