Skip to content

Instantly share code, notes, and snippets.

@quintona
Created November 25, 2013 10:37
Show Gist options
  • Save quintona/7639451 to your computer and use it in GitHub Desktop.
Save quintona/7639451 to your computer and use it in GitHub Desktop.
Implementation of the aggregation test from first principles using a basic Monoid
trait M[A] {
def op( a1: A, a2: A): A
def zero: A
}
val sumIntMonoid = new M[Int]{
val zero = 0
def op(a1:Int, a2:Int) = a1 + a2
}
val maxIntMonoid = new M[Int]{
val zero = Int.MinValue
def op(a1:Int, a2:Int) = if(a1>a2)a1 else a2
}
val monoids = List(sumIntMonoid, maxIntMonoid)
val l = List(1,2,3)
l.foldLeft(monoids.map(_.zero))((t,x) => monoids.zip(t).map(p => p._1.op(p._2,x)))

To break down that comprehension a bit:

Fold into the list using the monoid's zero as the initial values. The anon function will take a list and a scala as parameters (t,x). Zip the monoids with the parsed accumulator value which will provide a tuple containing the monoid and the accumulator value that is appropriate for that monoid. You can now apply the monoid operation to the accumulated value and x.

The result will be a list containing the results for each monoid applied to the set.

res16: List[Int] = List(6, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment