Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

scala - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...