Created
September 17, 2012 09:46
-
-
Save seanparsons/3736483 to your computer and use it in GitHub Desktop.
Kleisli composition is to flatMap as function composition is to map.
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
scala> import scalaz._ | |
import scalaz._ | |
scala> import Scalaz._ | |
import Scalaz._ | |
scala> val a = (value: Int) => value * 2 | |
a: Int => Int = <function1> | |
scala> val b = (value: Int) => value + 1 | |
b: Int => Int = <function1> | |
scala> 1.some.map(a).map(b) | |
res0: Option[Int] = Some(3) | |
// Compose the functions together. | |
scala> val ab = a.andThen(b) | |
ab: Int => Int = <function1> | |
// Is the same as "1.some.map(a).map(b)". | |
scala> 1.some.map(ab) | |
res1: Option[Int] = Some(3) | |
scala> val c = Kleisli((value: Int) => (value * 2).some) | |
c: scalaz.Kleisli[Option,Int,Int] = scalaz.KleisliFunctions$$anon$18@6b997837 | |
scala> val d = Kleisli((value: Int) => (value + 1).some) | |
d: scalaz.Kleisli[Option,Int,Int] = scalaz.KleisliFunctions$$anon$18@6f3ee250 | |
scala> 1.some.flatMap(c).flatMap(d) | |
res2: Option[Int] = Some(3) | |
// Compose the functions together. | |
scala> val cd = c.andThen(d) | |
cd: scalaz.Kleisli[Option,Int,Int] = scalaz.KleisliFunctions$$anon$18@25e9a396 | |
// Is the same as "1.some.flatMap(c).flatMap(d)". | |
scala> 1.some.flatMap(cd) | |
res3: Option[Int] = Some(3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment