Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala - Analog of Haskell's sequence [duplicate]

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!

like image 733
Matt W-D Avatar asked Oct 05 '22 07:10

Matt W-D


1 Answers

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)
like image 107
4lex1v Avatar answered Oct 09 '22 16:10

4lex1v