Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of options: equivalent of sequence in Scala?

What is the equivalent of Haskell's sequence in Scala? I want to turn list of options into an option of list. It should come out as None if any of the options is None.

List(Some(1), None, Some(2)).???     --> None
List(Some(1), Some(2), Some(3)).???  --> Some(List(1, 2, 3))
like image 299
luntain Avatar asked Jul 19 '11 16:07

luntain


People also ask

Is a list a Seq in Scala?

Seq has many subclasses including Queue, Range, List, Stack, and LinkedList. A List is a Seq that is implemented as an immutable linked list.

What is the difference between list and Seq in Scala?

Scala's sequence is equivalent to Java's List , while Scala's list is equivalent to Java's LinkedList . Both collections can store information, yet the sequence has a few extra highlights over the list . In Scala, a list is a particular collection that is streamlined and regularly utilized in functional programming.

What is a sequence in Scala?

Sequence is an iterable collection of class Iterable. It is used to represent indexed sequences that are having a defined order of element i.e. guaranteed immutable. The elements of sequences can be accessed using their indexes.


2 Answers

Scalaz defines sequence.

Here's an example:

scala> import scalaz._
import scalaz._

scala> import Scalaz._
import Scalaz._

scala> List(Some(1), None, Some(2)).sequence
res0: Option[List[Int]] = None

scala> List(some(1), some(2), some(3)).sequence
res1: Option[List[Int]] = Some(List(1, 2, 3))

Note that in the second example, you have to use Scalaz's some function to create a Some -- otherwise, the List is constructed as List[Some[Int]], which results in this error:

scala> List(Some(1), Some(2), Some(3)).sequence
<console>:14: error: could not find implicit value for parameter n: scalaz.Applicative[N]
       List(Some(1), Some(2), Some(3)).sequence

The Scalaz some(a) and none functions create Some and None values of type Option[A].

like image 170
mpilquist Avatar answered Oct 03 '22 06:10

mpilquist


If you want a solution for just List and Option rather a general monad then following will do the job,

def sequence[T](l : List[Option[T]]) = 
  if (l.contains(None)) None else Some(l.flatten)

REPL session,

scala> sequence(List(Some(1), None, Some(2)))
res2: Option[List[Int]] = None

scala> sequence(List(Some(1), Some(2), Some(3)))
res3: Option[List[Int]] = Some(List(1, 2, 3)) 

Update 20/8/2014

Just use Scalaz ...

like image 38
Miles Sabin Avatar answered Oct 03 '22 05:10

Miles Sabin