Last active
August 29, 2015 14:02
-
-
Save zhangxu/c3afad5a6299c1ccea06 to your computer and use it in GitHub Desktop.
Scalaz Validation and For-comprehension
This file contains 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
#!/usr/bin/env scalas | |
/*** | |
scalaVersion := "2.11.0" | |
scalacOptions += "-language:_" | |
libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.0.6" | |
*/ | |
import scala.math.sqrt | |
import scalaz._, Scalaz._ | |
def sqroot(d: Double): Validation[String, Double] = if (d >=0) sqrt(d).success else s"$d lt 0".fail | |
def inverse(d: Double): Validation[String, Double] = if (d == 0) "is 0".fail else (1 / d).success | |
def compute(d: Double): Validation[String, Double] = | |
for { | |
x <- sqroot(d) | |
y <- inverse(x) | |
} yield y | |
println(compute(-1.0)) | |
println(compute(0.0)) | |
println(compute(2.0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment