Skip to content

Instantly share code, notes, and snippets.

@vvviiimmm
Created February 17, 2017 23:16
Show Gist options
  • Save vvviiimmm/208695e141340ddd7951c405de7ee85d to your computer and use it in GitHub Desktop.
Save vvviiimmm/208695e141340ddd7951c405de7ee85d to your computer and use it in GitHub Desktop.
// Our interface
trait Monoid[A] {
def zero: A
def plus(a: A, b: A): A
}
// Implementation for integers
implicit object IntegerMonoid extends Monoid[Int] {
override def zero: Int = 0
override def plus(a: Int, b: Int): Int = a + b
}
// Implementation for strings
implicit object StringMonoid extends Monoid[String] {
override def zero: String = ""
override def plus(a: String, b: String): String = a.concat(b)
}
// Could be implementation for custom classes, etc..
// Our generic function that knows which implementation to use based on type parameter 'A'
def sum[A](values: Seq[A])(implicit ev: Monoid[A]): A = values.foldLeft(ev.zero)(ev.plus)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment