Created
February 17, 2017 23:16
-
-
Save vvviiimmm/208695e141340ddd7951c405de7ee85d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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