Skip to content

Instantly share code, notes, and snippets.

@seanparsons
Created September 17, 2012 09:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanparsons/3736483 to your computer and use it in GitHub Desktop.
Save seanparsons/3736483 to your computer and use it in GitHub Desktop.
Kleisli composition is to flatMap as function composition is to map.
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