What is the scala analog of Haskell's sequence
function?
http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:sequence
sequence
is defined in Haskell as follows:
sequence :: Monad m => [m a] -> m [a]
sequence ms = foldr k (return []) ms
where
k m m' = do { x <- m; xs <- m'; return (x:xs) }
Here are some uses:
ghci> sequence [Just 1, Just 2, Nothing, Just 3]
Nothing
ghci> sequence [[1,2],[3,4],[5,6]]
[[1,3,5],[1,3,6],[1,4,5],[1,4,6],[2,3,5],[2,3,6],[2,4,5],[2,4,6]]
Thanks in advance!
If you don't want to use scalaz, then you can implement it by yourself
def map2[A,B,C](a: Option[A], b: Option[B])(f: (A,B) => C): Option[C] =
a.flatMap { x => b.map { y => f(x, y) } }
def sequence[A](a: List[Option[A]]): Option[List[A]] =
a.foldRight[Option[List[A]]](Some(Nil))((x,y) => map2(x,y)(_ :: _))
Or an alternative implementation with traverse
def traverse[A, B](a: List[A])(f: A => Option[B]): Option[List[B]] =
a.foldRight[Option[List[B]]](Some(Nil))((h,t) => map2(f(h),t)(_ :: _))
def sequence[A](seq: List[Option[A]]): Option[List[A]] = traverse(seq)(identity)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With