选项列表:相当于Scala中的序列? [英] List of options: equivalent of sequence in Scala?

查看:74
本文介绍了选项列表:相当于Scala中的序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Haskell的 <$ Scala中的c $ c> sequence ?我想将选项列表变成列表选项。如果任何选项是 None ,它应该以 None 出现。

 列表(一些(1),无,一些(2))。 - >无
列表(一些(1),一些(2),一些(3))。 - > Some(List(1,2,3))


解决方案

如果你想为List和Option提供一个解决方案,而不是一个普通的monad,那么下面的工作就可以完成,
$ b $ pre $ def $ sequence def [T] (l:List [Option [T]])=
if(l.contains(None))None else Some(l.flatten)

REPL会话,

  scala>序列(List(Some(1),None,Some(2)))
res2:Option [List [Int]] = None

scala>序列(List(Some(1),Some(2),Some(3)))
res3:Option [List [Int]] = Some(List(1,2,3))



更新20/8/2014



只需使用Scalaz .. 。


What is the equivalent of Haskell's sequence in Scala? I want to turn list of options into an option of list. It should come out as None if any of the options is None.

List(Some(1), None, Some(2)).???     --> None
List(Some(1), Some(2), Some(3)).???  --> Some(List(1, 2, 3))

解决方案

If you want a solution for just List and Option rather a general monad then following will do the job,

def sequence[T](l : List[Option[T]]) = 
  if (l.contains(None)) None else Some(l.flatten)

REPL session,

scala> sequence(List(Some(1), None, Some(2)))
res2: Option[List[Int]] = None

scala> sequence(List(Some(1), Some(2), Some(3)))
res3: Option[List[Int]] = Some(List(1, 2, 3)) 

Update 20/8/2014

Just use Scalaz ...

这篇关于选项列表:相当于Scala中的序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆