Skip to content

Instantly share code, notes, and snippets.

@larsrh
Forked from channingwalton/gist:3230464
Created August 2, 2012 20:54
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 larsrh/3240574 to your computer and use it in GitHub Desktop.
Save larsrh/3240574 to your computer and use it in GitHub Desktop.
Example of Kleisli composition of Either
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")
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment