Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

For me, intuitivelly, sliding(n) would return a sliding window of n elements if available. With the current implementation, I need to perform an extra check to make sure I don't get a list of 1 or 2 elements.

scala> val xs = List(1, 2)
xs: List[Int] = List(1, 2)

scala> xs.sliding(3).toList
res2: List[List[Int]] = List(List(1, 2))

I expected here an empty list instead. Why is sliding() implemented this way instead?

like image 793
Adrian Avatar asked Oct 31 '11 19:10

Adrian


2 Answers

It was a mistake, but wasn't fixed as of 2.9. Everyone occasionally makes design errors, and once one gets into the library it's a nontrivial task to remove it.

Workaround: add a filter.

xs.sliding(3).filter(_.size==3).toList
like image 78
Rex Kerr Avatar answered Sep 21 '22 07:09

Rex Kerr


You can "work around" this by using the GroupedIterator#withPartial modifier.

scala> val xs = List(1, 2)
xs: List[Int] = List(1, 2)

scala> xs.iterator.sliding(3).withPartial(false).toList
res7: List[Seq[Int]] = List()

(I don't know why you need to say xs.iterator but xs.sliding(3).withPartial(false) does not work because you get an Iterator instead of a GroupedIterator.

like image 37
Emil Sit Avatar answered Sep 20 '22 07:09

Emil Sit