Skip to content

Instantly share code, notes, and snippets.

@PavelZaytsev
Last active December 2, 2018 10:12
Show Gist options
  • Save PavelZaytsev/d1efad6db8d9ae9a762f556edadc3228 to your computer and use it in GitHub Desktop.
Save PavelZaytsev/d1efad6db8d9ae9a762f556edadc3228 to your computer and use it in GitHub Desktop.
case class Writer[W, A](run: (W, A))
trait Monoid[A] {
def combine(a: A, b: A): A
def empty: A
}
object Writer {
def >==>[W: Monoid[W], A, B, C](a: A => Writer[W, B],
b: B => Writer[W, C]): A => Writer[W, C] = {
input: A =>
val writerB: Writer[W, B] = a(input)
flatMap(writerB)(b)
}
def run[W: Monoid[W], A]: Writer[W, A] => (W, A) = {
case Writer((a, w)) => (a, w)
}
def map[A, W: Monoid[W], B](wa: Writer[W, A])(f: A => B): Writer[W, B] = {
val (w, a) = wa.run
Writer((w, f(a)))
}
def flatMap[A, W: Monoid[W], B](wa: Writer[W, A])(
f: A => Writer[W, B]): Writer[W, B] = {
val (a, w) = wa.run
f(a)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment