Scala conditional list construction

collections, scala

Solution

How about yielding a Lists?

@inline def cond[T]( p : => Boolean, v : T ) : List[T] = if(p) v::Nil else Nil

and then using them as this:

List(1,2,3) ++ cond(false, 3 ) ++ List(4)

Problem

I'm using Scala 2.9.2, and would like to construct a list based on some conditions. Consider the following, where cond is some function taking a predicate p and a value of type T (in this case t3): ``` t1 :: t2 :: cond( p, t3 ) :: t4 ``` The behaviour I want is as follows. If p is true, this should give: ``` List[T]( t1, t2, t3, t4 ) ``` If p evaluates to false, this should give: ``` List[T]( t1, t2, t4 ) ``` I'm probably thinking about this completely the wrong way, but I'm struggling to come up with an elegant solution. I could involve Options everywhere and then filter, but that's makes the code rather harder to read: ``` def cond[T]( p : => Boolean, v : T ) : Option[T] = { p match { case true => Some( v ) case false => None } } ``` This allows the following: ``` scala> ( Some( 1 ) :: Some( 2 ) :: cond( true, 3 ) :: Some( 4 ) :: Nil ).flatten res4: List[Int] = List(1, 2, 3, 4) scala> ( Some( 1 ) :: Some( 2 ) :: cond( false, 3 ) :: Some( 4 ) :: Nil ).flatten res5: List[Int] = List(1, 2, 4) ``` However, it's not the most elegant solution, as it requires the user to wrap all of the their non-conditional elements in Some( ) and also to remember to do the flatten at the end. Can anyone think of a more elegant solution?

Original source