Skip to content

Instantly share code, notes, and snippets.

@rohinp
Created January 17, 2017 08:38
Show Gist options
  • Save rohinp/1fda395b3f55ad5a895f093a3ee84cca to your computer and use it in GitHub Desktop.
Save rohinp/1fda395b3f55ad5a895f093a3ee84cca to your computer and use it in GitHub Desktop.
//we have our monoid
trait Monoid[T] {
def associative(t1:T,t2:T):T
def zero:T
}
// lets have an implimentaion for int type
implicit val IntSumMonoid = new Monoid[Int] {
def associative(t1:Int,t2:Int): t1 + t2
def zero:Int = 0
}
//here is how our function will look now
def summ[T](xs:List[T])(implicit val m:Monoid[T]):T = xs.foldLeft(m.zero)(m.associative)
//this is how we can call our polymorphic function
//no need to pass the second parameter as its implicit
summ(List(1,2,3,4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment