문제

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?

도움이 되었습니까?

해결책

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)

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top