Created
October 6, 2011 00:07
-
-
Save CampingScorpion/1266126 to your computer and use it in GitHub Desktop.
Typeclassed Writer Monad
This file contains 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
case class Writer[A, D](value: A, diary: D)(implicit m: Monoid[D]) { | |
def flatMap[B](f: A => Writer2[B, D]) = f(value) match { | |
case Writer(result, d) => Writer(result, m.append(diary, d) | |
} | |
def map[B](f: A => B) = Writer[B, D](f(value), diary) | |
} | |
trait Monoid[T] { | |
def zero: T | |
def append(a: T, b: T): T | |
} | |
object Monoid { | |
implicit val StringMonoid = new Monoid[St ring] { | |
override def zero = "" | |
override def append(s1: String, s2: String) = s1 + s2 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment