Wednesday 23 April 2014

A neat Scala code snippet for depth aggregation

case class Price(val value: Double) extends AnyVal
case class Qty(val value: Int) extends AnyVal
case class Depth(price: Price, qty: Qty)

object Agg {
  def aggregate(in: List[Depth]) = in.foldLeft(List[Depth]())((l, c) => {
    if (l.isEmpty) List(c)
    else if (l.head.price == c.price) l updated (0, Depth(l.head.price, Qty(l.head.qty.value+c.qty.value)))
    else c +: l
  }).reverse
}

No comments:

Blog Archive