Created
January 28, 2016 15:11
-
-
Save pimeys/8d83447a1becccf1eb70 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import scalaz._ | |
trait Monoid[A] { | |
def mappend(a1: A, a2: A): A | |
def mzero: A | |
} | |
object Monoid { | |
implicit val IntMonoid: Monoid[Int] = new Monoid[Int] { | |
def mappend(a: Int, b: Int): Int = a + b | |
def mzero: Int = 0 | |
} | |
implicit val StringMonoid: Monoid[String] = new Monoid[String] { | |
def mappend(a: String, b: String): String = a + b | |
def mzero = "" | |
} | |
} | |
trait FoldLeft[F[_]] { | |
def foldLeft[A, B](xs: F[A], b: B, f: (B, A) => B): B | |
} | |
object FoldLeft { | |
implicit val FoldLeftList: FoldLeft[List] = new FoldLeft[List] { | |
def foldLeft[A, B](xs: List[A], b: B, f: (B, A) => B) = xs.foldLeft(b)(f) | |
} | |
} | |
trait MonoidOp[A] { | |
val F: Monoid[A] | |
val value: A | |
def |+|(a2: A) = F.mappend(value, a2) | |
} | |
object Main extends App { | |
implicit def toMonoidOp[A: Monoid](a: A): MonoidOp[A] = new MonoidOp[A] { | |
val F: Monoid[A] = implicitly[Monoid[A]] | |
val value: A = a | |
} | |
def sum[M[_]: FoldLeft, A: Monoid](xs: M[A]): A = { | |
val m = implicitly[Monoid[A]] | |
val fl = implicitly[FoldLeft[M]] | |
fl.foldLeft(xs, m.mzero, m.mappend) | |
} | |
def plus[A: Monoid](a: A, b: A): A = implicitly[Monoid[A]].mappend(a, b) | |
println(sum(List("a", "b", "c"))) | |
println(sum(List(1, 2, 3))) | |
println(plus(666, 666)) | |
println("a" |+| "b") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment