【问题标题】:Ruby to Scala code translation - Sorting in ScalaRuby 到 Scala 代码翻译 - 在 Scala 中排序
【发布时间】:2018-10-23 09:08:33
【问题描述】:

我正在将一些代码从 Ruby 转换为 Scala。问题是我一生中从未编写过 Ruby。进展顺利,但现在我到达了一条我不知道的线,因为我是 Scala 的新手,我不了解排序机制。 所以我想把这条红宝石线翻译成scala:

fronts[last_front].sort! {|x,y| crowded_comparison_operator(x,y)}

frontsVector[Vector[Map[String, Any]]]

last_frontInt

crowded_comparison_operator(x,y) 返回 -1、0 或 1,x 和 y 为 Map[String, Any]

【问题讨论】:

  • 你看过the docs for sortBy吗?
  • 当然,但是crowded_comparison_operator(x,y) 需要两个参数,这让我很困惑。对不起,我在 Scala/Java 中有点菜鸟

标签: ruby scala sorting translate code-translation


【解决方案1】:

标准 Scala 集合有两种可能性:

  • crowded_comparison_operator-1, 0, 1 输出转换为布尔值,告诉您第一个元素是否小于第二个元素,然后使用sortWith
  • 定义一个新的Ordering,将其显式传递给sorted 方法。

sortWith 方法

第一个元素小于第二个元素当且仅当crowded_comparison_operator 返回-1,所以你可以这样做:

fronts(last_front).sortWith{ (x, y) => crowded_comparison_operator(x, y) < 0 }

sorted定义一个Ordering

sorted 方法采用隐式 Ordering 参数。您可以定义自己的自定义排序,并显式传递它:

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 开始):

fronts(last_front).sorted(
  (x: Vector[Map[String, Any], y: Vector[Map[String, Any]]) => 
    crowded_comparison_operator(x, y)
)

请注意,正如@mikej 所指出的,Ruby 的sort! 对数组进行就地排序。这不适用于不可变向量,因此您必须相应地调整代码。

【讨论】:

  • 这个答案很棒!唯一要添加的是 Ruby 中的 sort! 执行就地排序。 Scala 中没有等效项,因此您可能需要调整 Scala 的其他部分以允许返回新的 Vector[Map[String, Any]] 而不是修改原始的。
  • @mikej 啊,谢谢,这是一个重要的区别。不幸的是,这不能轻易改变,因为Vector 是不可变的。感谢您指出这一点。
  • Scala 2.12开始,你可以只写fronts(last_front).sorted(crowded_comparison_operator)作为最后一个(假设crowded_comparison_operator是一个方法;如果它是一个函数,你可能需要fronts(last_front).sorted(crowded_comparison_operator(_, _)))。
  • @BrianMcCutchon 谢谢,已更新。我假设 crowded_comparison_operator 不是一个实际的方法名称,而是一个 ruby​​ 内联函数文字的冗长主体的占位符。因此我包含了显式类型注释Vector[Map[String, Any]],否则编译器会因为“错误:缺少参数类型”而对我发牢骚。
猜你喜欢
  • 1970-01-01
  • 2012-11-25
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多