I have a code such as:
val strs = List("hello", "andorra", "trab", "world")
def f1(s: String) = !s.startsWith("a")
def f2(s: String) = !s.endsWith("b")
val result = strs.filter(f1).filter(f2)
now, f1 and f2 should be applied based on a condition, such as:
val tmp1 = if (cond1) strs.filter(f1) else strs
val out = if (cond2) tmp1.filter(f2) else tmp1
is there a nicer way to do this, without using a temporary variable tmp1
?
one way would to filter based on a list of functions, such as:
val fs = List(f1 _,f2 _)
fs.foldLeft(strs)((fn, list) => list.filter(fn))
but then I would need to build a list of functions based on the conditions (and so, I would move the problem of using a temporary string list variable, to using a temporary function list variable (or I should need to use a mutable list)).
I am looking something like this (of course this does not compile, otherwise I would already have the answer to the question):
val result =
strs
.if(cond1, filter(f1))
.if(cond2, filter(f2))