Skip to content

Instantly share code, notes, and snippets.

@noelmarkham
Created September 18, 2012 16:03
Show Gist options
  • Save noelmarkham/3743931 to your computer and use it in GitHub Desktop.
Save noelmarkham/3743931 to your computer and use it in GitHub Desktop.
Kleisli composition
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))
@seanparsons
Copy link

andThen and arrows in this case are the same, the arrows are an alternative.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment