scala new Range,步长为零

发布于 2024-09-11 02:20:06 字数 275 浏览 3 评论 0原文

这真的应该被禁止吗(以及为什么)?

scala> val r2 = 15 until (10, 0)

java.lang.IllegalArgumentException: requirement failed

scala> new Range(10,15,0)

java.lang.IllegalArgumentException: requirement failed
    at scala.Predef$.require(Predef.scala:133)

Is(and why) this really should be prohibited with exception?

scala> val r2 = 15 until (10, 0)

java.lang.IllegalArgumentException: requirement failed

scala> new Range(10,15,0)

java.lang.IllegalArgumentException: requirement failed
    at scala.Predef$.require(Predef.scala:133)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

诠释孤独 2024-09-18 02:20:08

这是否(以及为什么)真的应该被禁止(例外)?

引用 scaladoc

Range 类表示范围 [start;end) 内的整数值,具有非零步长值步长。排序也类似于序列(支持长度和包含)。

这个限制是有道理的。步长为零的范围始终是无限的,并且仅包含下界值。尽管有人可能认为无限范围是可能的(惰性求值),但范围上限的概念将被视为荒谬的。步长为 0 的范围根本就不是范围,即使它无限长,因为上限并不重要。

因此,如果人们真的想要单个值的无限流,Scala 理所应当地迫使我们更加明确。

Is(and why) this really should be prohibited with exception?

Quoting from scaladoc:

The Range class represents integer values in range [start;end) with non-zero step value step. Sort of acts like a sequence also (supports length and contains).

This restriction makes sense. A range with step-size zero would always be infine and just consist of the lower bound value. Whereas one could argue that infinite ranges are possible (lazy evaluation), the concept of an upper bound in the range would be taken ad absurdum. A range with step 0 is simply not a range, even if it's infinitely long, because the upper bound has no importance.

So if one really wants an infinite stream of a single value, Scala rightfully forces us to be more explicit.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文