Created
March 8, 2017 09:58
-
-
Save meddulla/f4a8f0bf834088c1bc087a9f0da23028 to your computer and use it in GitHub Desktop.
Monoids
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
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