我正在寻找一种更通用的解决方案,该方案利用monad(可能还有monoid)来实现与 if( xs.contains(None) ) None else Some(xs.flatten)用于类型Seq[Option[A]]的xs.
I'm looking for a more general solution which exploits monads (and monoids possibly) to achieve the same as if( xs.contains(None) ) None else Some(xs.flatten) does for xs of type Seq[Option[A]].
如何使用Scalaz做到这一点?我觉得我缺少明显的东西.
How can I do that with Scalaz? I feel like I'm missing something evident.
推荐答案拥有两个单子既不足够(对于M)又绰绰有余(对于N)—当然,这加起来还不够—但是,如果M具有Traverse实例,而N具有Applicative实例,则可以使用sequence.例如:
Having two monads is both not enough (for M) and more than enough (for N)—which adds up to not enough, of course—but if M has a Traverse instance and N has an Applicative instance, you can use sequence. For example:
import scalaz._, Scalaz._ def foo[A](xs: List[Option[A]]): Option[List[A]] = xs.sequence这具有您想要的语义.请注意,我使用的是List而不是Seq,因为Scalaz 7不再为Seq提供必要的Traverse实例(尽管您可以轻松编写自己的实例).
This has the semantics you want. Note that I'm using List instead of Seq, since Scalaz 7 no longer provides the necessary Traverse instance for Seq (although you could easily write your own).
您已经注意到,以下内容不会编译:
As you've noticed, the following won't compile:
List(Some(1), Some(45)).sequence如果在其中扔None也可以:
scala> List(Some(1), None, Some(45)).sequence res0: Option[List[Int]] = None这是因为推断出的List(Some(1), Some(45))类型将是List[Some[Int]],而我们没有Applicative实例用于Some.
This is because the inferred type of List(Some(1), Some(45)) will be List[Some[Int]], and we don't have an Applicative instance for Some.
Scalaz提供了一个方便的some方法,该方法的工作方式与Some.apply相似,但是为您提供了已经键入为Option的内容,因此您可以编写以下内容:
Scalaz provides a handy some method that works like Some.apply but gives you something that's already typed as an Option, so you can write the following:
scala> List(some(1), some(45)).sequence res1: Option[List[Int]] = Some(List(1, 45))无需额外输入.
更多推荐
如果A和B是单子,如何将A [B [C]]转换为B [A [C]]?
发布评论