Bohtvaroh

Blogger - Scalaz Motivation - 8

Jun 1st, 2012
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.44 KB | None | 0 0
  1. object Monoid {
  2.   implicit object IntMonoid extends Monoid[Int] {
  3.     def mzero = 0
  4.     def mappend(a: Int, b: Int) = a + b
  5.   }
  6.  
  7.   implicit object StringMonoid extends Monoid[String] {
  8.     def mzero = ""
  9.     def mappend(a1: String, a2: String) = a1 + a2
  10.   }
  11. }
  12.  
  13. def sum[T](xs: List[T])(implicit m: Monoid[T]): T = xs.foldLeft(m.mzero)(m.mappend)
  14.  
  15. p(sum(List(1, 2, 3))) // prints ###> 6
  16. p(sum(List("lamb", "da"))) // prints ###> lambda
Advertisement
Add Comment
Please, Sign In to add comment