scala - Haskell 序列的模拟

标签 scala haskell monads

这个问题在这里已经有了答案:





List of options: equivalent of sequence in Scala?

(7 个回答)


8年前关闭。




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

提前致谢!

最佳答案

如果你不想使用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)

关于scala - Haskell 序列的模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16204842/

相关文章:

段落的正则表达式匹配

function - Haskell IO传递给另一个功能

scala - 在 Future 的 flatMap 中抛出异常?

haskell - 为什么 Haskell 这么大?

ide - 如何为 Scala 项目配置 jEdit?

haskell - 如何映射和连接文件路径?

c# - IO monad 在像 C# 这样的语言中有意义吗

haskell - 测试返回 Maybe Monad 的函数

scala - 使 SBT 中的非详尽匹配编译失败

scala - 使用 Rapture Http 获取请求