scala - Haskell序列的模拟

时间:2013-04-25 01:12:29

标签: scala haskell monads

Haskell sequence函数的scala模拟是什么? http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:sequence

sequence在Haskell中定义如下:

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) }

以下是一些用途:

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]]

提前致谢!

1 个答案:

答案 0 :(得分:3)

如果您不想使用scalaz,那么您可以自己实现

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)(_ :: _))

或者使用遍历

的替代实现
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)