Convert a List of Options to an Option of List using Scalaz

Posted by Rafael de F. Ferreira on Stack Overflow See other posts from Stack Overflow or by Rafael de F. Ferreira
Published on 2010-04-02T20:28:52Z Indexed on 2010/04/02 20:33 UTC
Read the original article Hit count: 438

Filed under:
|
|

The following function transforms a list of Option[T] into a list of Some[T], in the case where all members are Some's, or None, in the case where there is at least one None member. I guess the code is clearer that this explanation:

def lo2ol[T](lo: List[Option[T]]): Option[List[T]] = {
  lo.foldRight[Option[List[T]]](Some(Nil)){(o, ol) => (o, ol) match {
    case (Some(x), Some(xs)) => Some(x :: xs);
    case _ => None : Option[List[T]]; 
}}}

I remember seeing somewhere a similar example, but using Scalaz to simplify the code. How would it look like?

© Stack Overflow or respective owner

Related posts about scala

Related posts about scalaz