Last active
January 25, 2017 06:26
-
-
Save rohinp/95f3db105cd23c94dd78d2c152b3defb 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
trait Monoid[T] { | |
def assco(t1:T,t2:T):T | |
def zero:T | |
} | |
implicit val IntSumMnoid = new Monoid[Int] { | |
override def assco(t1: Int, t2: Int): Int = t1 + t2 | |
override def zero: Int = 0 | |
} | |
implicit val StringConcatMonoid = new Monoid[String] { | |
override def assco(t1: String, t2: String): String = t1 + t2 | |
override def zero: String = "" | |
} | |
//this was our code at step one | |
//def summ[T](l:List[T])(implicit a:AmazingThing[T]):T = l.foldLeft(a.zero)(a.assco) | |
//step one code cna be also written with type bound, as shown below. | |
//just a syntactical change and when it compiles it compiles to the same step one code | |
/*def summ[T:Monoid](l:List[T]):T = { | |
val a = implicitly[Monoid[T]] | |
l.foldLeft(a.zero)(a.assco) | |
}*/ | |
//Here we are using F[_] (higher kind) means we want to pass a Type which in turn will expect a Type | |
//as shown in the below case where FoldLeft is expecting a DataStructure(List) and | |
//that data structure(List) again expects a type | |
//F[_] underscore because our data structure can be of any type. kind of a wildcard | |
trait FoldLeft[F[_]] { | |
def foldLeft[A,B](xs:F[A],zero:B,f:(B,A) => B):B | |
} | |
//implimentation for list | |
implicit val FoldLeftList = new FoldLeft[List] { | |
override def foldLeft[A, B](xs: List[A], zero: B, f: (B, A) => B): B = | |
xs.foldLeft(zero)(f) | |
} | |
//here we go our polymorphic function | |
def summ[F[_]:FoldLeft, T:Monoid](l:F[T]):T = { | |
val a = implicitly[Monoid[T]] | |
val m = implicitly[FoldLeft[F]] | |
m.foldLeft(l,a.zero,a.assco) | |
} | |
summ(List(1,2,3,4)) | |
summ(List("1.","2.","3...")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment