Created
November 14, 2013 03:10
-
-
Save kevinmeredith/7460695 to your computer and use it in GitHub Desktop.
Example of composing Monoids from the book, "Functional Programming in Scala"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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