【问题标题】:Scala lift from List[A] to List[Option[A]]Scala 从 List[A] 提升到 List[Option[A]]
【发布时间】:2017-01-06 16:09:27
【问题描述】:

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

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

【问题讨论】:

  • def f[A](in: List[A]): List[Option[A]] = in.map(Some(_))?
  • @evan058 Some(_) 会给你Some(null) 当in 的某些元素是null 我怀疑这是OP 想要的。
  • 是的,我想我不知道 OP 想要什么。 @OP,你想要什么?您输入中的哪些值应该是None?有吗?
  • 实际上我不希望他们中的任何一个被评估为None。我希望将此功能与其他部分集成,以便库的用户无需担心 Option 框架
  • 我无法想象一个理智的理由为什么你会想要Some(null)...

标签: scala scalaz lifting


【解决方案1】:

不就是_.map(Option.apply)这么简单吗?

【讨论】:

  • 当然是!啊,如此简单的事情可以轻松地浪费一天,真是太神奇了。谢谢!
  • 所以Option.apply 知道null 应该是None。它还会映射到None 什么?
  • 哈,这是唯一的值:def apply[A](x: A): Option[A] = if (x == null) None else Some(x) (src)
【解决方案2】:

如果您希望所有元素都为 Some(...)(就像您在评论中提到的那样),请使用以下内容:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-21
    • 2013-05-21
    • 1970-01-01
    • 2012-09-18
    • 2019-12-09
    • 2015-03-13
    • 1970-01-01
    • 2016-09-16
    相关资源
    最近更新 更多