如果 n 小于大小,则 xs.sliding(n) 的行为不一致? [英] Inconsistent behaviour for xs.sliding(n) if n is less than size?

查看:42
本文介绍了如果 n 小于大小,则 xs.sliding(n) 的行为不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据scaladoc,sliding() 返回...一个迭代器生成大小为 size 的可迭代集合,如果元素少于 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."

对我来说,直觉上,sliding(n) 会返回一个包含 n 个元素的滑动窗口如果可用.对于当前的实现,我需要执行额外的检查以确保我没有得到 1 或 2 个元素的列表.

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))

我希望这里有一个空列表.为什么sliding() 以这种方式实现?

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

推荐答案

是一个错误,但是自 2.9 起未修复.每个人偶尔都会犯设计错误,一旦进入图书馆,将其删除是一项非同寻常的任务.

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

这篇关于如果 n 小于大小,则 xs.sliding(n) 的行为不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆