public
Last active

  • Download Gist
01.monoid.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
def sum1[A](as: List[A])(implicit m: Monoid[A]): A = as.foldRight(m.zero)(m.plus)
 
trait Monoid[A] {
def zero: A
def plus(a1: A, a2: A): A
}
 
implicit object IntMonoid extends Monoid[Int] {
def zero: Int = 0
 
def plus(a1: Int, a2: Int): Int = a1 + a2
}
 
implicit val StringMonoid = new Monoid[String] {
def plus(a1: String, a2: String): String = a1 + a2
 
def zero: String = ""
}
 
implicit def Tuple2Monoid[A, B](implicit ma: Monoid[A], mb: Monoid[B]): Monoid[(A, B)] = new Monoid[(A, B)] {
def plus(a1: (A, B), a2: (A, B)): (A, B) = {
val resultA = ma.plus(a1._1, a2._1)
val resultB = mb.plus(a1._2, a2._2)
(resultA, resultB)
}
 
def zero: (A, B) = (ma.zero, mb.zero)
}
 
println("result1: " + sum1(List(1, 2, 3)))
println("result2: " + sum1(List("a", "b", "c")))
println("result3: " + sum1(List(("a", 1), ("b", 2), ("c", 3))))
02.foldable.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
 
def sum2[F[_], A](as: F[A])(implicit m: Monoid[A], f: Foldable[F]): A = f.foldr(as, m.zero, m.plus)
 
trait Foldable[F[_]] {
def foldr[A, B](fa: F[A], b: B, f: (A, B) => B): B
}
 
implicit object ListFoldable extends Foldable[List] {
def foldr[A, B](fa: List[A], b: B, f: (A, B) => B): B = fa.foldRight(b)(f)
}
 
implicit object OptionFoldable extends Foldable[Option] {
def foldr[A, B](fa: Option[A], b: B, f: (A, B) => B): B = fa.toList.foldRight(b)(f)
}
 
println("result4: " + sum2(List(("a", 1), ("b", 2), ("c", 3))))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.