Created
January 17, 2017 08:38
-
-
Save rohinp/1fda395b3f55ad5a895f093a3ee84cca to your computer and use it in GitHub Desktop.
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
//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