Scala从列表[A]提升到列表[选项[A]]
在scala中,如何创建通用函数来执行以下操作: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
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()))
?@evan058Some())
会给你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)
()