小编and*_*ohn的帖子

删除冗余条目,scala方式

编辑:添加了一个事实,即列表已排序,并且实现"重复"会产生误导,将其替换为标题中的"冗余".

我有一个条目的排序列表,说明给定时间间隔内的生产值.以后声明完全相同的值的条目不会添加任何信息,可以安全地省略.

case class Entry(minute:Int, production:Double)
val entries = List(Entry(0, 100.0), Entry(5, 100.0), Entry(10, 100.0), Entry(20, 120.0), Entry(30, 100.0), Entry(180, 0.0))
Run Code Online (Sandbox Code Playgroud)

尝试使用scala 2.8集合函数,到目前为止,我有这个工作实现:

entries.foldRight(List[Entry]()) {
  (entry, list) => list match {
    case head :: tail if (entry.production == head.production) => entry :: tail
    case head :: tail => entry :: list
    case List() => entry :: List()
  }
}
res0: List[Entry] = List(Entry(0,100.0), Entry(20,120.0), Entry(30,100.0), Entry(180,0.0))
Run Code Online (Sandbox Code Playgroud)

任何意见?我错过了一些斯卡拉魔法吗?

scala

5
推荐指数
1
解决办法
853
查看次数

标签 统计

scala ×1