相关疑难解决方法(0)

使用Scalaz将选项列表转换为List选项

我想把a List[Option[T]]变成a Option[List[T]].函数的签名类型是

def lo2ol[T](lo: List[Option[T]]): Option[List[T]]
Run Code Online (Sandbox Code Playgroud)

预期的行为是将仅包含Somes 的列表映射到Some包含元素内部元素的列表Some.另一方面,如果输入列表至少有一个None,则预期的行为是返回None.例如:

scala> lo2ol(Some(1) :: Some(2) :: Nil)
res10: Option[List[Int]] = Some(List(1, 2))

scala> lo2ol(Some(1) :: None :: Some(2) :: Nil)
res11: Option[List[Int]] = None

scala> lo2ol(Nil : List[Option[Int]])
res12: Option[List[Int]] = Some(List())
Run Code Online (Sandbox Code Playgroud)

没有scalaz的示例实现将是:

def lo2ol[T](lo: List[Option[T]]): Option[List[T]] = {
  lo.foldRight[Option[List[T]]](Some(Nil)){(o, ol) => (o, ol) match {
    case (Some(x), Some(xs)) => Some(x :: xs);
    case _ => None : Option[List[T]]; 
}}} …
Run Code Online (Sandbox Code Playgroud)

scala option scalaz

28
推荐指数
2
解决办法
1万
查看次数

scala - Haskell 序列的模拟

Haskellsequence函数的 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) }
Run Code Online (Sandbox Code Playgroud)

以下是一些用途:

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]]
Run Code Online (Sandbox Code Playgroud)

提前致谢!

monads haskell scala

5
推荐指数
1
解决办法
739
查看次数

标签 统计

scala ×2

haskell ×1

monads ×1

option ×1

scalaz ×1