Commit 2cb48d27 authored by Haochen Xie's avatar Haochen Xie

ch10/Monoids.scala - implement ex 10.6

parent 983b9eb2
......@@ -64,8 +64,23 @@ object Monoids {
def concatenate[A](as: List[A], m: Monoid[A]): A =
foldMap(as, m)(Predef.identity)
def makePointedMonoid[A](op0: (A, A) => A) = new Monoid[Option[A]] {
override def op(o1: Option[A], o2: Option[A]): Option[A] = (o1, o2) match {
case (None, _) => o2
case (_, None) => o1
case (Some(a1), Some(a2)) => Some(op0(a1, a2))
}
override val zero: Option[A] = Option.empty
}
// Exercise 10.6
// well, for later
def foldLeft[A,B](as: List[A])(z: B)(f: (B, A) => B): B = {
foldMap(as, makePointedMonoid[B=>B]((g1, g2) => z => g2(g1(z))))(a => Some(z => f(z, a))).get(z)
}
def foldRight[A,B](as: List[A])(z: B)(f: (A, B) => B): B = {
foldMap(as, makePointedMonoid[B=>B]((g1, g2) => z => g1(g2(z))))(a => Some(z => f(a, z))).get(z)
}
// Exercise 10.7
def foldMapV[A,B](v: IndexedSeq[A], m: Monoid[B])(f: A => B): B =
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment