Skip to content

Instantly share code, notes, and snippets.

@zhangxu
Last active August 29, 2015 14:02
Show Gist options
  • Save zhangxu/c3afad5a6299c1ccea06 to your computer and use it in GitHub Desktop.
Save zhangxu/c3afad5a6299c1ccea06 to your computer and use it in GitHub Desktop.
Scalaz Validation and For-comprehension
#!/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