Scala从列表[A]提升到列表[选项[A]]

Scala从列表[A]提升到列表[选项[A]],scala,scalaz,lifting,Scala,Scalaz,Lifting,在scala中,如何创建通用函数来执行以下操作: f:List[A]=>List[Option[A]这不是像.map(Option.apply)那么简单吗?如果您希望所有元素都是某些(…)(如您在评论中提到的)那么简单,请使用以下内容: scala> def f[A](in: List[A]): List[Option[A]] = in.map(Some(_)) f: [A](in: List[A])List[Option[A]] scala> f(0 to 5 toList) w

在scala中,如何创建通用函数来执行以下操作:


f:List[A]=>List[Option[A]

这不是像
.map(Option.apply)
那么简单吗?

如果您希望所有元素都是
某些(…)
(如您在评论中提到的)那么简单,请使用以下内容:

scala> def f[A](in: List[A]): List[Option[A]] = in.map(Some(_))
f: [A](in: List[A])List[Option[A]]

scala> f(0 to 5 toList)
warning: there was one feature warning; re-run with -feature for details
res4: List[Option[Int]] = List(Some(0), Some(1), Some(2), Some(3), Some(4), Some(5))

scala> f(List("a", "b", null))
res5: List[Option[String]] = List(Some(a), Some(b), Some(null))
@2rs2ts的回答将为您提供:

scala> def f_2rs2ts[A](in: List[A]): List[Option[A]] = in.map(Option.apply)
f_2rs2ts: [A](in: List[A])List[Option[A]]

scala> f_2rs2ts(List("a", "b", null))
res6: List[Option[String]] = List(Some(a), Some(b), None)

def[A](in:List[A]):List[Option[A]=in.map(Some()))
?@evan058
Some())
会给你
Some(null)
的某个元素为
null
时,我怀疑OP想要什么。是的,我想我不知道OP想要什么@哦,你想要什么?您输入的值应该是
None
?它们中的任何一个?实际上,我不希望它们中的任何一个被评估为
None
。我希望此功能与其他部分集成,这样库的用户就不必担心Framework选项。我无法想象您想要
Some(null)
…当然是这样!啊,太神奇了,你怎么能轻松地把一天浪费在这么简单的事情上。谢谢所以
选项.apply
知道
null
应该是
None
。它还能映射到什么呢?
None
?Ha,这是唯一的值:
def apply[A](x:A):Option[A]=if(x==null)None-other一些(x)
()