Skip to content

Instantly share code, notes, and snippets.

@songpp
Created March 16, 2012 09:24
Show Gist options
  • Save songpp/2049259 to your computer and use it in GitHub Desktop.
Save songpp/2049259 to your computer and use it in GitHub Desktop.
from Scalaz Video
package org.songpp.fp
/*
* scala
*/
trait FoldLeft[F[_]] {
def foldLeft[A, B](xs: F[A], init: B, func: (B, A) => B): B
}
object FoldLeft {
implicit object FoldLeftList extends FoldLeft[List] {
def foldLeft[A, B](xs: List[A], init: B, func: (B, A) => B): B = xs.foldLeft(init)(func)
}
}
trait Monoid[T] {
def mappend(a: T, b: T): T
def mzero: T
}
object Monoid {
implicit object IntMonoid extends Monoid[Int] {
def mappend(a: Int, b: Int): Int = a + b
def mzero = 0
}
implicit object StringMonoid extends Monoid[String] {
def mappend(a: String, b: String): String = a + b
def mzero = ""
}
}
object Main {
def multmonoid = new Monoid[Int] {
def mappend(a: Int, b: Int): Int = a * b
def mzero = 1
}
def sum[M[_], T](xs: M[T])(implicit monoid: Monoid[T], fl: FoldLeft[M]) = fl.foldLeft(xs, monoid.mzero, monoid.mappend)
def p(a: Any) = println("===> " + a.toString())
def main(args: Array[String]): Unit = {
println()
p(sum(List(1, 2, 3, 4)))
p(sum(List(1, 2, 3, 4))(multmonoid, FoldLeft.FoldLeftList))
p(sum(List("a", "b", "c")))
println()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment