scalaz 验证和列表 monad [英] scalaz validation and list monad
本文介绍了scalaz 验证和列表 monad的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试提出类似于以下内容的内容:
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?
推荐答案
如果你有一个A
的验证列表,你可以把它变成一个A
列表的验证code> 使用 sequence
:
If you have a list of validations of A
, you can turn it into a validation of lists of A
using sequence
:
List(1, 2).map(s2).sequence[({type l[a]=Validation[String, a]})#l, Int]
(如果我理解正确的话).所以你得到
(if I understand the question correctly). So you get
val result = for {
i <- s
k <- List(1, 2).map(s2).sequence[({type l[a]=Validation[String, a]})#l, Int]
} yield "fine"
这篇关于scalaz 验证和列表 monad的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文