Inconsistent behaviour for xs.sliding(n) if n is less than size?

前端 未结 3 680
萌比男神i
萌比男神i 2020-12-20 12:08

According to scaladoc, sliding() returns... \"An iterator producing iterable collections of size size, except the last and the only element will be truncated if

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-20 12:49

    EDIT:

    Check Rex's answer (which is the correct one). I'm leaving this just because (as Rex said on the comments) it was the original (wrong) idea behind that design decision.


    I don't know why you would expect an empty list there, returning the full list seems like the best result, consider this example:

    def slidingWindowsThing(windows : List[List[Int]]) { // do your thing
    

    For this methods you probably want all these calls to work:

    slidingWindowsThing((1 to 10).sliding(3))
    
    slidingWindowsThing((1 to 3).sliding(3))
    
    slidingWindowsThing((1 to 1).sliding(3))
    

    This is why the method defaults to a list of size list.length instead of Nil (empty list).

提交回复
热议问题