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

后端 未结 1 1745
醉话见心
醉话见心 2020-12-30 21:21

I found myself lately using sliding(n,n) when I need to iterate collections in groups of n elements without re-processing any of them. I was wondering if it would be more co

相关标签:
1条回答
  • 2020-12-30 22:11

    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.

    0 讨论(0)
提交回复
热议问题