Scalaでは、次の操作を実行する汎用関数を作成するにはどうすればよいですか:
f: List[A] ==> List[Option[A]]
と同じくらい簡単ではありません_.map(Option.apply)
か?
すべての要素を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)