Scala 中什么时候一个 Set 小于另一个 Set?
我想比较 Scala 中两个集合的基数。由于某些东西有时在 Scala 中“正常工作”,因此我尝试在集合之间使用 <
。它似乎通过了,但我无法从结果中看出任何意义。
示例:
scala> Set(1,2,3) < Set(1,4)
res20: Boolean = true
- 它返回什么?
- 在 API 中哪里可以阅读有关此方法的信息?
- 为什么它没有列在 scala.collection.immutable.Set 下的任何地方?
更新:甚至集合中元素的顺序(??)似乎也很重要:
scala> Set(2,3,1) < Set(1,3)
res24: Boolean = false
scala> Set(1,2,3) < Set(1,3)
res25: Boolean = true
I wanted to compare the cardinality of two sets in Scala. Since stuff sometimes "just work" in Scala, I tried using <
between the sets. It seems to go through, but I can't make any sense out of the result.
Example:
scala> Set(1,2,3) < Set(1,4)
res20: Boolean = true
- What does it return?
- Where can I read about this method in the API?
- Why isn't it listed anywhere under
scala.collection.immutable.Set
?
Update: Even the order(??) of the elements in the sets seem to matter:
scala> Set(2,3,1) < Set(1,3)
res24: Boolean = false
scala> Set(1,2,3) < Set(1,3)
res25: Boolean = true
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不适用于 2.8。在 Scala 2.7 上,发生的情况是这样的:
换句话说,在
scala.Predef
上定义了一个隐式转换,它是从Iterable[A]< 为所有 Scala 代码“导入”的。 /code> 到
Ordered[Iterable[A]]
,前提是存在隐式A =>;已订购[A]
可用。鉴于集合的可迭代顺序未定义,您无法真正对其进行太多预测。例如,如果添加元素以使集合大小大于四,您将得到完全不同的结果。
This doesn't work with 2.8. On Scala 2.7, what happens is this:
In other words, there's an implicit conversion defined on
scala.Predef
, which is "imported" for all Scala code, from anIterable[A]
to anOrdered[Iterable[A]]
, provided there's an implicitA => Ordered[A]
available.Given that the order of an iterable for sets is undefined, you can't really predict much about it. If you add elements to make the set size bigger than four, for instance, you'll get entirely different results.
如果你想比较基数,直接这样做:
If you want to compare the cardinality, just do so directly:
我对 Scala 的了解并不广泛,但是做了一些测试,我得到以下结果:
这告诉我
<
来自特征Ordered
。更多提示:也就是说,
Set
被评估为Iterable
,因为可能存在从 Iterable[A] 到 Ordered[Iterable[A]] 的隐式转换,但是我不再确定......测试不一致。例如,这两个可能建议进行一种字典顺序比较:1 相等,2 相等,3 小于 4。
但这些则不然:
我认为正确的答案是在
Ordered 特征正确:除了比较其 hashCode 之外,集合之间没有任何
<
实现:My knowledge of Scala is not extensive, but doing some test, I get the following:
That tells me that
<
comes from the traitOrdered
. More hints:That is, the
Set
is evaluated into anIterable
, because maybe there is some implicit conversion from Iterable[A] to Ordered[Iterable[A]], but I'm not sure anymore... Tests are not consistent. For example, these two might suggest a kind of lexicographical compare:1 is equal, 2 is equal, 3 is less than 4.
But these ones don't:
I think the correct answer is that found in the
Ordered
trait proper: There is no implementation for<
between sets more than comparing their hashCode: