public
Created

StringBuilder Monoid

  • Download Gist
gistfile1.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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"))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.