Skip to content

Instantly share code, notes, and snippets.

@akirillov
Last active August 29, 2015 14:19
Show Gist options
  • Save akirillov/ca3ba557cfc65a1d7f84 to your computer and use it in GitHub Desktop.
Save akirillov/ca3ba557cfc65a1d7f84 to your computer and use it in GitHub Desktop.
Pimp My Library + Monoid List Operation
trait Monoid[A]{
def mappend(a1: A, a2: A): A
def mzero: A
}
object Monoid {
implicit val IntMonoid: Monoid[Int] = new Monoid[Int] {
def mappend(a: Int, b: Int): Int = a + b
def mzero: Int = 0
}
implicit val StringMonoid: Monoid[String] = new Monoid[String] {
def mappend(a: String, b: String): String = a + b
def mzero: String = ""
}
}
trait MonoidList[A] {
val F: Monoid[A]
val value: List[A]
def sum[A]() = value.foldLeft(F.mzero)(F.mappend)
}
object MonoidList{
implicit def toMonoidList[A: Monoid](xs: List[A]): MonoidList[A] = new MonoidList[A] {
val value = xs
val F = implicitly[Monoid[A]]
}
}
object Example {
def main(args: Array[String]): Unit = {
val intList: MonoidList[Int] = List(1,2,3)
println(intList.sum())
val stringList: MonoidList[String] = List("a","b","c")
println(stringList.sum())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment