Skip to content

Instantly share code, notes, and snippets.

@RaasAhsan
Created January 11, 2014 07:15
Show Gist options
  • Save RaasAhsan/8368036 to your computer and use it in GitHub Desktop.
Save RaasAhsan/8368036 to your computer and use it in GitHub Desktop.
A very simple Writer monad written in Scala.
class Writer[A](runWriter: (A, String)) {
def apply(x: (A, String)): Writer[A] = new Writer[A](x)
def run = runWriter
def flatMap[B](x: A => Writer[B]): Writer[B] = {
val (a: A, b: String) = runWriter
val (y: B, z: String) = x(a).run
new Writer[B]((y, b + z))
}
def map[B](f: A => B): Writer[B] = {
val (a: A, b: String) = runWriter
val (y: B, z: String) = f(a)
new Writer[B]((y, z))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment