EDIT: I just remembered that anti-aliasing has the same effect as my filter and map
I am using Scala 2.9.2 and would like to build a list based on some conditions.
Consider the following, where cond is a function taking a predicate p and a value of type T (in this case, t3):
t1 :: t2 :: cond( p, t3 ) :: t4
The behavior 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 probably think about it completely wrong, but I try my best to come up with an elegant solution. I could use the parameters everywhere and then filter, but this makes the code more difficult to read:
def cond[T]( p : => Boolean, v : T ) : Option[T] = { p match { case true => Some( v ) case false => None } }
This allows:
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, this is not the most elegant solution, since it requires the user to wrap all his non-conditional elements in Some (), and also remember to do the smoothing at the end. Can anyone think of a more elegant solution?