Created
April 12, 2011 21:55
-
-
Save retronym/916518 to your computer and use it in GitHub Desktop.
Code Samples from http://www.meetup.com/Zurich-Scala/events/17083233/
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
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)))) |
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
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)))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment