Ruby 到 Scala 代码转换 - 在 Scala 中排序 [英] Ruby to Scala code translation - Sorting in Scala
问题描述
我正在将一些代码从 Ruby 转换为 Scala.问题是我这辈子从来没有给 Ruby 编程过.它进展顺利,但现在我遇到了一个我不知道的行,因为我是 Scala 的新手,我不了解排序机制.所以我想把这个 ruby 行翻译成 Scala:
I'm converting some code from Ruby to Scala. Problem is that I never programmed Ruby in my life. It's going well, but now I reached a line that I don't know because I'm new in Scala and I don't understand the sorting mechanism. So I want to translate this ruby line to scala:
fronts[last_front].sort! {|x,y| crowded_comparison_operator(x,y)}
fronts
是 Vector[Vector[Map[String, Any]]]
last_front
是一个 Int
crowded_comparison_operator(x,y)
返回 -1、0 或 1,x 和 y 是 Map[String, Any]
crowded_comparison_operator(x,y)
returns -1, 0 or 1, x and y are Map[String, Any]
推荐答案
标准 Scala 集合有两种可能性:
You have two possibilities with standard Scala collections:
- 将
crowded_comparison_operator
的-1, 0, 1
输出转换为布尔值,告诉您第一个元素是否小于第二个元素,然后使用sortWith
. - 定义一个新的
Ordering
,将其显式传递给sorted
方法.
- Convert the
-1, 0, 1
output ofcrowded_comparison_operator
into a boolean that tells you whether the first element is less than the second element, then usesortWith
. - define a new
Ordering
, pass it explicitly to thesorted
method.
sortWith
方法
The sortWith
method
第一个元素小于第二个元素当且仅当 crowded_comparison_operator
返回 -1,所以你可以这样做:
The first element is less than the second element if and only if crowded_comparison_operator
returns -1, so you could do this:
fronts(last_front).sortWith{ (x, y) => crowded_comparison_operator(x, y) < 0 }
<小时>
为sorted
sorted
方法采用一个隐式的 Ordering
参数.您可以定义自己的自定义排序,并明确传递它:
The sorted
method takes an implicit Ordering
parameter. You can define your own custom ordering, and pass it explicitly:
import scala.math.Ordering
fronts(last_front).sorted(new Ordering[Vector[Map[String, Any]]] {
def compare(
x: Vector[Map[String, Any]],
y: Vector[Map[String, Any]]
): Int = crowded_comparison_operator(x, y)
})
或更短,Scala 版本支持 SAM(从 2.11.5 开始,如果我没记错的话):
or shorter, with scala versions supporting SAM (since 2.11.5, if I remember correctly):
fronts(last_front).sorted(
(x: Vector[Map[String, Any], y: Vector[Map[String, Any]]) =>
crowded_comparison_operator(x, y)
)
请注意,正如@mikej 所指出的,Ruby 的 sort!
就地对数组进行排序.这不适用于不可变向量,因此您必须相应地调整代码.
Note that, as @mikej has pointed out, Ruby's sort!
sorts the array in-place. This cannot work for an immutable vector, so you have to adjust your code accordingly.
这篇关于Ruby 到 Scala 代码转换 - 在 Scala 中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!