Scala 接受匿名比较器吗?
我如何接受一个函数作为参数传递给 scala 中的 Vector.sortBy() ?
目前我有一个这样的函数:
private def buildTree(data: Vector[Data2D]): Node = {
var sorted: Vector[Data2D] = data.sortBy(_.x)
// etc...
}
但是,我想传递“_.x”(对x排序)或“_.y”作为函数的参数,所以我可以这样做:
private def buildTree(data: Vector[Data2D], comparator): Node = {
var sorted: Vector[Data2D] = data.sortBy(comparator)
// etc...
if(comparator == _.x){
buildTree(data, _.y)
}
}
所以我会就像检查当前的“比较器”是什么,然后递归地将 y 坐标的比较器传递给它。
我希望这一点很清楚。在Java中我会把它写成:
private Node buildTree(List<Data2D> data, Comparator<Data2D> comparator) {
// Sorted on x or y
Collections.sort(data, comparator);
// ... snip ...
if (comparator instanceof XComparator) {
// Recurse
Node subtree = buildTree(data, YComparator.INSTANCE);
ret.setSubtree(subtree);
}
return ret;
}
// Then build tree is called like:
Node root = tree.buildTree(data, XComparator.INSTANCE)
How can I accept a function to pass to Vector.sortBy() in scala as an argument?
Currently I have a function like this:
private def buildTree(data: Vector[Data2D]): Node = {
var sorted: Vector[Data2D] = data.sortBy(_.x)
// etc...
}
However, I would like to pass either "_.x" (sort on x) or "_.y" as an argument to the function, so I can do something like this:
private def buildTree(data: Vector[Data2D], comparator): Node = {
var sorted: Vector[Data2D] = data.sortBy(comparator)
// etc...
if(comparator == _.x){
buildTree(data, _.y)
}
}
So I would like to check what the current "comparator" is, and then recurse passing it the comparator for the y coordinate.
I hope this is clear. In Java I would write it as:
private Node buildTree(List<Data2D> data, Comparator<Data2D> comparator) {
// Sorted on x or y
Collections.sort(data, comparator);
// ... snip ...
if (comparator instanceof XComparator) {
// Recurse
Node subtree = buildTree(data, YComparator.INSTANCE);
ret.setSubtree(subtree);
}
return ret;
}
// Then build tree is called like:
Node root = tree.buildTree(data, XComparator.INSTANCE)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,您想要一个
Ordering
。像这样:sortBy
方法只是为您创建一个Ordering
。sortBy(_.x)
相当于sorted(Ordering.by(_.x))
。Actually, you want an
Ordering
. Like this:The
sortBy
method just creates anOrdering
for you.sortBy(_.x)
is equivalent tosorted(Ordering.by(_.x))
.如果您检查文档,您会发现
sortBy
采用一个参数:f: A =>; B。看起来像一个通用函数,它接受
A
作为参数并生成B
。那么,让我们尝试一下:它定义了我们想要的两个函数。现在我们可以调用
和测试
(尽管我建议将两个比较器作为参数传递,而不是搜索特定的常量)。
If you check the docs, you see that
sortBy
takes one argument:f: A => B
. Looks like a generic function that takesA
as an argument and produces aB
. So, let's give that a try:which defines the two functions that we want. Now we can call
and test
(though I would recommend passing in both comparators as arguments rather than searching for specific constants).