What is the best way to add Option
s to a List
.
Here is my first try :
def append[A](as: List[A], maybeA1 : Option[A], maybeA2: Option[A]) : List[A] = as ++ maybeA1.toList ++ maybeA2.toList
Con : it creates 2 tmp List
(I know .toList() is optional because there is an implicit conversion from Option[A] to Iterable[A])
Another try is
def append2[A](ls: List[A], maybeA : Option[A]) : List[A] = maybeA.map(_ :: ls).getOrElse(ls)
def append[A](as: List[A], maybeA1 : Option[A], maybeA2: Option[A]) : List[A] = append2(append2(as, maybeA1), maybeA2)
Better perf but less readable…
Is there another way ?
def combine[A](s: Seq[A], o: Option[A]) = (s /: o)(_ :+ _)
def combineAll[A](s: Seq[A], os: Option[A]*) = (s /: os)(combine)
combineAll(List(1), Some(2), None, Some(3))
//res0: Seq[Int] = List(1, 2, 3)
Use List.++
or List.++:
:
def append[A](o:Option[A],l:List[A]):List[A] = l ++ o
def prepend[A](o:Option[A],l:List[A]):List[A] = o ++: l
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With