我有一个代码,例如:
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)
现在,应根据条件应用 f1 和 f2,例如:
val tmp1 = if (cond1) strs.filter(f1) else strs
val out = if (cond2) tmp1.filter(f2) else tmp1
有没有更好的方法来做到这一点,而不使用临时变量
tmp1
?一种方法是根据函数列表进行过滤,例如:
val fs = List(f1 _,f2 _)
fs.foldLeft(strs)((fn, list) => list.filter(fn))
但是随后我需要根据条件构建一个函数列表(因此,我会将使用临时字符串列表变量的问题移至使用临时函数列表变量(或者我应该需要使用可变列表) )。
我看起来像这样(当然这不会编译,否则我已经有了问题的答案):
val result =
strs
.if(cond1, filter(f1))
.if(cond2, filter(f2))
最佳答案
您可以轻松使用隐式类为您提供以下语法:
val strs = List("hello", "andorra", "trab", "world")
def f1(s: String) = !s.startsWith("a")
def f2(s: String) = !s.endsWith("b")
val cond1 = true
val cond2 = true
implicit class FilterHelper[A](l: List[A]) {
def ifFilter(cond: Boolean, f: A => Boolean) = {
if (cond) l.filter(f) else l
}
}
strs
.ifFilter(cond1, f1)
.ifFilter(cond2, f2)
res1: List[String] = List(hello, world)
我会用
if
作为方法名称,但它是一个保留字。
关于scala,根据几个条件过滤集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17406454/