Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Options to a List

What is the best way to add Options 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 ?

like image 277
Yann Moisan Avatar asked Nov 08 '14 16:11

Yann Moisan


2 Answers

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)
like image 156
Ryoichiro Oka Avatar answered Nov 01 '22 05:11

Ryoichiro Oka


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
like image 25
Ferrules Avatar answered Nov 01 '22 04:11

Ferrules