0

In scala, how can i create a general purpose function to perform the following operation:

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

raul ferreira
  • 886
  • 7
  • 21

2 Answers2

6

Isn't it as simple as _.map(Option.apply)?

2rs2ts
  • 10,662
  • 10
  • 51
  • 95
  • of course it is! ahh it's amazing how you can easily waste a day with something so much simple. thanks! – raul ferreira Jan 06 '17 at 16:15
  • So `Option.apply` knows that `null` should be `None`. What else would it map to `None`? – evan.oman Jan 06 '17 at 16:21
  • 1
    Ha, that is the only value: `def apply[A](x: A): Option[A] = if (x == null) None else Some(x)` ([src](https://github.com/scala/scala/blob/v2.12.1/src/library/scala/Option.scala#L25)) – evan.oman Jan 06 '17 at 16:28
3

If you want all elements to be Some(...) (like you mentioned in your comment) use something like this:

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's answer would give you:

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)
evan.oman
  • 5,922
  • 22
  • 43