Skip to content

Instantly share code, notes, and snippets.

@meddulla
Created March 8, 2017 09:58
Show Gist options
  • Save meddulla/f4a8f0bf834088c1bc087a9f0da23028 to your computer and use it in GitHub Desktop.
Save meddulla/f4a8f0bf834088c1bc087a9f0da23028 to your computer and use it in GitHub Desktop.
Monoids
object Monoids {
trait Semigroup[A] {
def add(x: A, y: A): A
}
trait Monoid[A] extends Semigroup[A] {
def zero: A
}
object Monoid {
def apply[A: Monoid]: Monoid[A] = implicitly
}
implicit object Integers extends Monoid[Int] {
override val zero = 0
override def add(x: Int, y: Int) = x + y
}
implicit object Strings extends Monoid[String] {
override val zero = ""
override def add(x: String, y: String) = x + y
}
def aggregate[A: Monoid](xs: Iterable[A]): A =
xs.fold(Monoid[A].zero)(Monoid[A].add)
def main(args: Array[String]): Unit = {
aggregate(Seq(1, 2, 3))
aggregate(Seq("abc", "xyz"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment