Create a gist now

Instantly share code, notes, and snippets.

StringBuilder Monoid
object Monoid {
implicit val StringBuilderMonoid = new Monoid[StringBuilder] {
override def zero = new StringBuilder("")
override def append(sb1: StringBuilder, sb2: StringBuilder) = {
val delimiter = if (sb1.toString == "" ||
sb2.toString == "") ""
else ", "
sb1.append(delimiter).append(sb2)
}
}
}
Writer(22, new StringBuilder("")).flatMap { n =>
Writer(n + 2, new StringBuilder("plus two"))
}.flatMap { n =>
Writer(n * 4, new StringBuilder("times four"))
})
// => Writer(96, StringBuilder("plus two, times four"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment