scalaz 验证和列表 monad
我试图提出类似于以下内容的内容:
val s: Validation[String, Int] = 1.success
def s2(i: Int): Validation[String, Int] = i.success
val result = for {
i <- s
j <- List(1, 2)
k <- s2(j)
} yield "fine";
上面的代码无法编译,我理解,从语法上讲它没有意义。
我正在尝试以单子方式执行验证列表。我该如何实现这一目标?
I am trying to come up with something similar to the following:
val s: Validation[String, Int] = 1.success
def s2(i: Int): Validation[String, Int] = i.success
val result = for {
i <- s
j <- List(1, 2)
k <- s2(j)
} yield "fine";
The above code does not compile and I understand, syntactically it does not make sense.
I am trying to execute a list of validations in a monadic way. How do I achieve that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您有
A
的验证列表,则可以使用sequence
将其转换为A
列表的验证:(如果我理解正确提问)。所以你得到
If you have a list of validations of
A
, you can turn it into a validation of lists ofA
usingsequence
:(if I understand the question correctly). So you get
您似乎正在使用验证来消除副作用。这不是它的目的。您可以在函数式编程中使用返回值。
for 理解中的验证在成功时继续,但在失败时中断并返回失败。
You seem to be using validation for the side effect. This is not what its ment for. You use the return values in functional programming.
Validation in a for comprehension continues with on success, but breaks of at a failure and returns the failure.