Skip to content

Instantly share code, notes, and snippets.

@folone
Created October 18, 2012 12:27
Show Gist options
  • Save folone/3911467 to your computer and use it in GitHub Desktop.
Save folone/3911467 to your computer and use it in GitHub Desktop.
Writer exercise
import scalaz._, Scalaz._
case class Writer[W: Monoid, +A](run: (A, W)) {
def map[B](f: A ⇒ B): Writer[W, B] =
Writer {
val (a, w) = run
(f(a), w)
}
def flatMap[B](f: A ⇒ Writer[W, B]): Writer[W, B] =
Writer {
val (a, w1) = run
val (b, w2) = f(a).run
(b, w1 |+| w2)
}
}
object Writer {
def point[W: Monoid, A](a: A): Writer[W, A] = Writer((a, Monoid[W].zero))
def sequence[W: Monoid, A](t: List[Writer[W, A]]): Writer[W, List[A]] =
t.foldLeft(point[W, List[A]](Nil: List[A])) { (acc, v) ⇒
for {
x ← v
xs ← acc
} yield x::xs
}
def filterM[W: Monoid, A](p: A ⇒ Writer[W, Boolean], a: List[A]): Writer[W, List[A]] =
a match {
case x::xs ⇒ for {
flg ← p(x)
ys ← filterM(p, xs)
} yield if(flg) x::ys else ys
case Nil ⇒ point(Nil)
}
def tell[W: Monoid](w: W): Writer[W, Unit] = Writer(((), w))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment