public
Last active

Example of Kleisli composition of Validation

  • 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 23 24 25 26
object KleisliValidation extends App {
import scalaz._
import Scalaz._
import scala.util.control.Exception._
 
type EValidation[+T] = Validation[String, T]
implicit val binding = new Bind[EValidation] {
def map[A, B](fa: EValidation[A])(f: A => B): EValidation[B] = fa.map(f)
def bind[A, B](fa: EValidation[A])(f: A => EValidation[B]): EValidation[B] = fa.flatMap(f)
}
def toDouble(s: String):EValidation[Double] = allCatch.either(s.toDouble).fold(_.toString.fail, _.success)
def sqrt(d: Double):EValidation[Double] = if (d >= 0) math.sqrt(d).success else "sqrt(%s) is too complex for me".format(d).fail
val composed = Kleisli(toDouble _) >==> (sqrt(_))
println(composed("2"))
println(composed("-2"))
println(composed("hi"))
}
 
/*
Success(1.4142135623730951)
Failure(sqrt(-2.0) is too complex for me)
Failure(java.lang.NumberFormatException: For input string: "hi")
*/

BTW this requires scalaz 7

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.