This works on scalaz 7.0.6, but not on the latest release of scalaz, 7.2.6.
import scalaz._, Scalaz._
def allDigits(s: String): Validation[String, String] =
if (s.forall(_.isDigit)) s.success else "Not all digits".failure
def maxSizeOfTen(s: String): Validation[String, String] =
if (s.length <= 10) s.success else "Too big".failure
def toInt(s: String) = try s.toInt.success catch {
case _: NumberFormatException => "Still not an integer".failure
}
val validated1 = for {
x <- allDigits("4234")
y <- maxSizeOfTen(x)
z <- toInt(y)
} yield z
I get these errors on scalaz 7.2.6:
value flatMap is not a member of scalaz.Validation[String,String]
x <- allDigits("4234")
value flatMap is not a member of scalaz.Validation[String,String]
y <- maxSizeOfTen(x)
...
How do I make it work on the latest version of scalaz?
Update: Solution based on the accepted answer:
import scalaz._, Scalaz._
def allDigits(s: String): \/[String, String] =
if (s.forall(_.isDigit)) s.right else "Not all digits".left
def maxSizeOfTen(s: String): \/[String, String] =
if (s.length <= 10) s.right else "Too big".left
def toInt(s: String) = try s.toInt.right catch {
case _: NumberFormatException => "Still not an integer".left
}
val validated1 = for {
x <- allDigits("4234")
y <- maxSizeOfTen(x)
z <- toInt(y)
} yield z
Validation is not supposed to be used with a flatMap
, because it aims to accumulate the failures and therefore has Applicative
instance for independent (context-free) computations. \/
is supposed to be used in your case (dependent (or context-sensitive) computations).
Still, by adding this import, you can achieve what you want:
import Validation.FlatMap._
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With