Skip to content

Instantly share code, notes, and snippets.

@pimeys
Created January 28, 2016 15:11
Show Gist options
  • Save pimeys/8d83447a1becccf1eb70 to your computer and use it in GitHub Desktop.
Save pimeys/8d83447a1becccf1eb70 to your computer and use it in GitHub Desktop.
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