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);
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With