Created
September 18, 2012 16:03
-
-
Save noelmarkham/3743931 to your computer and use it in GitHub Desktop.
Kleisli composition
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._, Scalaz._ | |
import scalaz._ | |
import Scalaz._ | |
scala> def str(x: Int): Option[String] = Some(x.toString) | |
str: (x: Int)Option[String] | |
scala> def toInt(x: String): Option[Int] = Some(x.toInt) | |
toInt: (x: String)Option[Int] | |
scala> def double(x: Int): Option[Double] = Some(x * 2) | |
double: (x: Int)Option[Double] | |
scala> val arrows = Kleisli(str) >=> Kleisli(toInt) >=> Kleisli(double) | |
arrows: scalaz.Kleisli[Option,Int,Double] = scalaz.KleisliFunctions$$anon$18@58741a85 | |
scala> arrows(6) | |
res0: Option[Double] = Some(12.0) | |
scala> val andThen = Kleisli(str) andThen Kleisli(toInt) andThen Kleisli(double) | |
andThen: scalaz.Kleisli[Option,Int,Double] = scalaz.KleisliFunctions$$anon$18@3146d556 | |
scala> andThen(10) | |
res1: Option[Double] = Some(20.0) | |
scala> 1.some.flatMap(arrows) | |
res2: Option[Double] = Some(2.0) | |
scala> 1.some.map(arrows) | |
res3: Option[Option[Double]] = Some(Some(2.0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
andThen and arrows in this case are the same, the arrows are an alternative.