Created
March 23, 2014 00:24
-
-
Save cvogt/9716490 to your computer and use it in GitHub Desktop.
Simplified Monoid implementation of http://stackoverflow.com/questions/4765532/what-does-abstract-over-mean
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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