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]].
How can I do that with Scalaz? I feel like I’m missing something evident.
Having two monads is both not enough (for
M) and more than enough (forN)—which adds up to not enough, of course—but ifMhas aTraverseinstance andNhas anApplicativeinstance, you can usesequence. For example:This has the semantics you want. Note that I’m using
Listinstead ofSeq, since Scalaz 7 no longer provides the necessaryTraverseinstance forSeq(although you could easily write your own).As you’ve noticed, the following won’t compile:
Although it’s fine if you throw a
Nonein there:This is because the inferred type of
List(Some(1), Some(45))will beList[Some[Int]], and we don’t have anApplicativeinstance forSome.Scalaz provides a handy
somemethod that works likeSome.applybut gives you something that’s already typed as anOption, so you can write the following:No extra typing necessary.