gpt4 book ai didi

scalaz 7.2.6 flatMap 不是验证方法吗?

转载 作者:行者123 更新时间:2023-12-04 19:30:33 25 4
gpt4 key购买 nike

这适用于 scalaz 7.0.6,但不适用于最新版本的 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

我在 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)
...

我如何使它在最新版本的 scalaz 上工作?

更新:基于已接受答案的解决方案:
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

最佳答案

验证不应与 flatMap 一起使用,因为它旨在累积失败,因此具有 Applicative独立(无上下文)计算的实例。 \/应该在您的情况下使用(依赖(或上下文相关)计算)。
尽管如此,通过添加此导入,您可以实现您想要的:import Validation.FlatMap._

关于scalaz 7.2.6 flatMap 不是验证方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39465402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com