Remove redundant entries, scala method

Edit: The fact is added that the list is sorted, and the implementation of "duplicate" is misleading, is replaced by "redundant" in the header.

I have a sorted list of records indicating the production value for a given interval. Entries indicating the same value later do not add any information and can be easily excluded.

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))

Experimenting with the functions of the scala 2.8 collection, so far I have this working implementation:

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))

Any comments? Did I miss some scala magic?

+5
source share
3 answers

, zip -ping , .

collect, , , - e2. (collect Scala 2.8, - partialMap)

scala> entries.head :: ((entries zip entries.tail).collect { 
           case (Entry(_, p1), e2@Entry(_, p2)) if p1 != p2 => e2 
       })
res13: List[Entry] = List(Entry(0,100.0), Entry(20,120.0), Entry(30,100.0), Entry(180,0.0))

UPDATE , .

+9

zipped Tuple2, ( ), zip . - , , , , ( ):

entries.take(1) :::
(entries,entries.drop(1)).zipped.filter(_.production != _.production)._2

, , , , . take drop .

, , , , .

+3

, O (n ^ 2) zipping, n ^ 2 , [Double, Int]. "" "" . "". , , , , , O (n log (n)) .

"mymap + = production → minute", , , " ()". O (log (n)), O (n log (n)).

By the way, you can use the [Double, Entry] map to map derived values ​​directly to your Entry structures. Then you can easily get the list, if necessary, by pulling the map values ​​directly from the map and sorting by any entry element (if necessary).

0
source

All Articles