Created
December 2, 2012 07:27
-
-
Save etorreborre/4187596 to your computer and use it in GitHub Desktop.
Monoids for the option of a function
This file contains 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
import scalaz._ | |
import Scalaz._ | |
trait A { | |
def increment: A | |
} | |
case class A1(i: Int) extends A { | |
def increment = A1(i+20) | |
} | |
val f0: Option[A => A] = None | |
val f1: Option[A => A] = Some((a: A) => a.increment) | |
val g0: Option[Int => Int] = None | |
val g1: Option[Int => Int] = Some((a: Int) => a + 20) | |
implicit val m = new Monoid[A => A] { | |
def zero = identity | |
def append(f1: A => A, f2: =>(A => A)) = f1 andThen f2 | |
} | |
// m kicks in | |
(~f0).apply(A1(3)) // A1(3) | |
(~f1).apply(A1(3)) // A1(23) | |
// the monoid kicking in is the Monoid[Option[T]] where T is a Monoid | |
// in the case of Int => Int, it's the Monoid created from a function returning a type B where B | |
// has a Monoid (Int in this case | |
(~g0).apply(3) // 0 | |
(~g1).apply(3) // 23 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
note that If you change the types of f0,f1,g0,g1 From Option[Int => Int] to Option[Endo[Int]] then you get the same behavior as your 'm' monoid