Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to elegantly concatenate an Option[List] to a List?

Tags:

scala

I tried to write those 3 codes without success :

aList.foldLeft(List()){(accu, element) => map.get(elment):::accu}
aList.foldLeft(List()){(accu, element) => if (!map.get(element).isEmpty) map.get(element):::accu}
aList.foldLeft(List()){(accu, element) => map.get(elment).exists(_:::accu)}

Does anyone know how to do to concatenate an Option to a list?

like image 210
bruce Avatar asked Oct 13 '12 04:10

bruce


2 Answers

To concatenate an Option with a List you can just do option.toList ++ list

To concatenate an Option[List[A]] with a List[A] optionOfList.toList.flatten ++ list

The basic idea being you can always convert an option to a list of 0 or one element which makes it easy to combine them with lists in different ways.

like image 148
Ratan Sebastian Avatar answered Oct 26 '22 13:10

Ratan Sebastian


Sprinkle some scalaz:

import scalaz._; import Scalaz._

And setup:

scala> val optList = some(List(1, 2, 3, 4)
optList: Option[List[Int]] = Some(List(1, 2, 3, 4))

scala> val list = List(5, 6, 7)
list: List[Int] = List(5, 6, 7)

Then I can do:

scala> ~optList ::: list
res0: List[Int] = List(1, 2, 3, 4, 5, 6, 7)

Basically ~ is a unary method attached to Option[A] where there is a zero for the type A. The zero for list is of course, Nil

like image 21
oxbow_lakes Avatar answered Oct 26 '22 13:10

oxbow_lakes