Skip to content

Instantly share code, notes, and snippets.

@kevinmeredith
Created November 14, 2013 03:10
Show Gist options
  • Select an option

  • Save kevinmeredith/7460695 to your computer and use it in GitHub Desktop.

Select an option

Save kevinmeredith/7460695 to your computer and use it in GitHub Desktop.
Example of composing Monoids from the book, "Functional Programming in Scala"
object ComposingMonoids {
// Beginning of monoid compoisition (from FP in Scala)
// https://github.com/pchiusano/fpinscala/.../.../17.answer.scala
def productMonoid[A, B](A: Monoid[A], B: Monoid[B]): Monoid[(A, B)] = {
new Monoid[(A, B)] {
def op(x: (A,B), y: (A,B) ) = (A.op(x._1, y._1) , B.op(x._2, y._2))
val zero = (A.zero, B.zero)
}
}
val intMultiplication = new Monoid[Int] {
def op(a1: Int, a2: Int) = a1 * a2
val zero = 1
}
val concatenate = new Monoid[String] {
def op(a1: String, a2: String) = a1 + a2
val zero = ""
}
def main(args: Array[String]) = {
val x = (100, "hello")
val y = (200, "world")
val result: (Int, String) = productMonoid(intMultiplication, concatenate).op(x,y)
println("result: " + result)
assert(result._1 == 20000)
assert(result._2 == "helloworld")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment