如何在 Scala 中为 TreeSet 分配顺序而不重复我自己
我有这段 Scala 代码,它定义了一个排序并将其应用于 TreeSet。这部分编译得很好。
val acctOrdering = new Ordering[Account] {
def compare(acc1: Account, acc2: Account) {
// code to compare based on various criteria
}
}
private var accountSet = new TreeSet[Account]()(acctOrdering)
在代码的其他地方,我想根据我之前的顺序获取集合中的第一个元素(如果第一个元素没有产生我想要的结果,则稍后获取后续元素,尽管这通常是不必要的)指定的。我认为以下内容可以工作,但它没有编译:
val firstAccount = accountSet.min
错误是 “无法找到参数 cmp 的隐式值:Ordering[Account]”
但是,如果我在询问时再次指定排序对象对于最小值,它会编译:
val firstAccount = accountSet.min(acctOrdering)
我认为它会自动使用我在构造时给出的排序,并在添加到集合时增量排序,因此在调用 min< 时我不必再次指定排序/代码>。
我做错了什么?我需要在某处显式定义隐式函数吗?
I have this segment of Scala code which defines an ordering and applies it to a TreeSet. This part compiles fine.
val acctOrdering = new Ordering[Account] {
def compare(acc1: Account, acc2: Account) {
// code to compare based on various criteria
}
}
private var accountSet = new TreeSet[Account]()(acctOrdering)
Elsewhere in the code, I want to get the first element in the set (and later on get subsequent ones if the first one doesn't produce what I want, although that usually won't be necessary), based on the order I previously specified. I thought the following would work, but it didn't compile:
val firstAccount = accountSet.min
The error is "could not find implicit value for parameter cmp: Ordering[Account]"
However, if I specify the ordering object again when asking for the minimum, it compiles:
val firstAccount = accountSet.min(acctOrdering)
I thought it would have automatically used the ordering I gave at construction time, and incrementally sorting as I added to the set, so I wouldn't have to specify the ordering again when calling min
.
What am I doing wrong? Do I need to explicitly define an implicit function somewhere?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生的情况是,您假设
min
取决于集合的顺序,但事实并非如此。具体来说,min
和max
是几乎任何集合上都可用的通用方法,并且它们采用隐式Ordering
参数。但是,如果您尝试
firstKey
和lastKey
(它们是SortedSet
特定的方法),它们将无需传递任何隐式参数即可工作。编辑
您可能提出的一个问题是,如何确保您的
帐户
类型可以通过任何需要订购
的方法进行订购。您可以通过在Account
的对象伴生中放置隐式定义来实现此目的,如下所示:一旦这样做,您将不需要显式传递排序。
What is happening is that you are assuming
min
depends on the ordering of the set, but it doesn't. Specifically,min
andmax
are generic methods available on pretty much any collection, and they take an implicitOrdering
parameter.However, if you try
firstKey
andlastKey
, which areSortedSet
-specific methods, they'll work without having to pass any implicit.Edit
One question you might have posed is to how do you make sure your
Account
type can be ordered by any method expecting anOrdering
. You can do that by putting an implicit definition insideAccount
's object companion, like this:Once you do that, you won't need to pass the ordering explicitly.