public
Last active — forked from channingwalton/gist:3230464

Example of Kleisli composition of Either

  • Download Gist
gistfile1.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
object KleisliValidation extends App {
import scalaz._
import Scalaz._
import scala.util.control.Exception._
 
type EEither[+T] = Either[String, T]
def toDouble(s: String): EEither[Double] = allCatch.either(s.toDouble).fold(_.toString.left, _.right)
def sqrt(d: Double): EEither[Double] = if (d >= 0) math.sqrt(d).right else "sqrt(%s) is too complex for me".format(d).left
val composed = Kleisli(toDouble _) >==> sqrt
println(composed("2"))
println(composed("-2"))
println(composed("hi"))
}
 
/*
Right(1.4142135623730951)
Left(sqrt(-2.0) is too complex for me)
Left(java.lang.NumberFormatException: For input string: "hi")
*/

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.