Question

I found a blog post today that mention's scalaz's sequence function.

Couldn't you do something as simple as:

if (l contains None) None else l

If so, what would this function signature look like? contains is in SeqLike, right?

Also, from the blog post I thought sequence was going to be something similar to map, but one that would break once None is encountered. Is there something like this?

Was it helpful?

Solution

Yes you can definitely write the sequence function specialized to some specific data structure. The Scalaz version, however is as general as possible. So it will work for any combination of F and G for which F[G[A]] => G[F[A]] is possible.

The other function you're looking for is called traverse. It has the signature

def traverse[F[_]:Traverse,G[_]:Applicative,A,B](m: F[A], f: A => G[B]): G[F[B]]

x.traverse(f) is equivalent to x.map(f).sequence.

x.sequence is equivalent to x.traverse(a => a)

OTHER TIPS

Yes, you could, but it should be:

if (l contains None) None else Some(l.map(_.get))

The code in the blog post tries to write that function as general as possible (using scalaz' abstractions), so it will work not only for Options in a Seq.

[Edit] Corrected

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top