I'd try folding:
def merge(lotsOfColor: List[MyColor], delta: Double): List[MyColor] =
lotsOfColor.tail.foldLeft((List(lotsOfColor.head), lotsOfColor.head)) {
case ((mergedColors, lastColor), aColor) if (lastColor diff aColor) < delta =>
(mergedColors, lastColor merge aColor)
case ((mergedColors, _), aColor) => (aColor :: mergedColors, aColor)
}._1.reverse
Or, slightly different,
def merge(lotsOfColor: List[MyColor], delta: Double): List[MyColor] =
lotsOfColor.tail.foldLeft((List(lotsOfColor.head), lotsOfColor.head)) {
case ((mergedColors, lastColor), aColor) =>
if ((lastColor diff aColor) < delta)
(mergedColors, lastColor merge aColor)
else
(aColor :: mergedColors, aColor)
}._1.reverse
There's also another cool trick using ListBuffer in Scala, to avoid the reverse at the end:
import scala.collection.mutable.ListBuffer
def merge(lotsOfColor: List[MyColor], delta: Double): List[MyColor] =
lotsOfColor.tail.foldLeft((ListBuffer(lotsOfColor.head), lotsOfColor.head)) {
case ((mergedColors, lastColor), aColor) if (lastColor diff aColor) < delta =>
(mergedColors, lastColor merge aColor)
case ((mergedColors, _), aColor) =>
mergedColors += aColor
(mergedColors, aColor)
}._1.toList