score:34

Accepted answer

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.


Related Query

More Query from same tag