Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging elements in a scala list

I'm trying to port the following Java snippet to Scala. It takes a list of MyColor objects and merges all of the ones that are within a delta of each other. It seems like a problem that could be solved elegantly using some of Scala's functional bits. Any tips?

List<MyColor> mergedColors = ...;
MyColor lastColor = null;
for(Color aColor : lotsOfColors) {
  if(lastColor != null) {
    if(lastColor.diff(aColor) < delta) {
      lastColor.merge(aColor);
      continue;
    }
  }
  lastColor = aColor;
  mergedColors.add(aColor);
}
like image 855
Edward Dale Avatar asked Dec 08 '22 04:12

Edward Dale


1 Answers

Here's another recursive solution, which has the advantage of being tail recursive (so no chance of stack overflow) but on the downside does a lot of list manipulation, so may be wasteful. The call to reverse at the end is to put the output colors back in the input order, but isn't needed if you don't care about the ordering.

def processColors(colors: List[Color], delta: Double): List[Color] = {
  def process(in: List[Color], accum: List[Color]): List[Color] = in match {
      case x :: y :: ys if x.diff(y) < delta => process( x.merge(y) :: ys, accum )
      case x :: xs                           => process( xs, x :: accum )
      case Nil                               => accum
    }

  process(colors, Nil).reverse
}
like image 62
ams Avatar answered Dec 09 '22 18:12

ams