【问题标题】:Sort a collection of values based on another collection in a "Scala way"以“Scala 方式”基于另一个集合对一组值进行排序
【发布时间】:2020-03-20 11:09:57
【问题描述】:

我必须根据我作为另一个列表的子列表可用的一组键对一组值进行排序。 目前,我有以下代码可以正确完成这项工作。但是,它使用可变集合,我知道这不是在 Scala 中执行此操作的最佳方式。这样做的漂亮“Scala 方式”是什么? 谢谢。

var sorted: IndexedSeq[IndexedSeq[Any]]
//sortKeys is a list of lists containing sorting properties (index,descending/ascending) 
for (i <- (0 until sortKeys).reverse) {
      val index = sortKeys(i).get(i).getIndex
      val desc = sortKeys.get(i).descending
      if (desc) {
        sorted = sorted.sorted { (t1: IndexedSeq, t2: IndexedSeq) => -t1(index).asInstanceOf[Comparable[Any]].compareTo(t2(index)) }
      } else {
        sorted = sorted.sorted { (t1: IndexedSeq, t2: IndexedSeq) => t1(index).asInstanceOf[Comparable[Any]].compareTo(t2(index)) }
      }
    }

【问题讨论】:

  • 你能用你的实现写scalafiddle.io吗?我不明白。 (用示例粘贴您的代码,确保它可以编译,然后ctrl+s 并与我们分享链接)
  • 特别是 sorted 需要初始化为某些东西(可能是未排序的输入)
  • 是的,对不起,我忘了精确我假设 sorted 在开头包含所有未排序的值。为了便于阅读,我稍微简化了代码。这是一堂大课的一部分。

标签: scala sorting functional-programming


【解决方案1】:

粗略的草图:

val sortKeys = Seq( (1,true), (2, false))

val input = Seq( Array("a", "b", "c"), Array("a", "x", "c" )

sortKeys.foldRight(input){
  case ( (index, ascending), acc) =>
     acc.sortWith( (a,b) => if (ascending) a(index) > b(index)    
          else a(index) < b(index))
}

【讨论】:

  • 谢谢!我对此进行了调整以适应我的实现并且它起作用了。我不得不使用 sorted with compare to 而不是 sortBy 因为我的元素没有隐式排序。我错过了 foldRight... 这是关键
猜你喜欢
  • 2015-10-18
  • 1970-01-01
  • 2015-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多