【发布时间】: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