Skip to content

Instantly share code, notes, and snippets.

@cvogt
Created March 23, 2014 00:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cvogt/9716490 to your computer and use it in GitHub Desktop.
Save cvogt/9716490 to your computer and use it in GitHub Desktop.
trait Monoid[M] {
def zero: M
def add(m1: M, m2: M): M
}
trait Foldable[F[_]] {
def foldl[A, B](as: F[A], z: B, f: (B, A) => B): B
}
def mapReduce[F[_], A, B](as: F[A], m: Monoid[A])
(implicit ff: Foldable[F]) =
ff.foldl(as, m.zero, m.add)
val sum = new Monoid[Int] {
def zero = 0
def add(a: Int, b: Int) = a + b
}
val product = new Monoid[Int] {
def zero = 1
def add(a: Int, b: Int) = a * b
}
implicit val listFoldable = new Foldable[List] {
def foldl[A, B](as: List[A], z: B, f: (B, A) => B) = as.foldLeft(z)(f)
}
val sumOf123 = mapReduce(List(1,2,3), sum)
val productOf456 = mapReduce(List(4,5,6), product)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment