假设您希望进程签名不改变......
// continuing from the ops psuedocode
def process(data: Seq[Int], b1:Boolean, b2:Boolean, b3:Boolean): Seq[Int] = {
@tailrec
def loop (acc: Seq[Int], ops: List[Seq[Int] => Seq[Int]]): Seq[Int] = {
ops match {
case List () => acc
case head :: tail => loop (head(acc), tail)
}
}
loop (data, List(( b1,op1 _), (b2,op2 _),(b3,op3 _)).filter{ _._1 }.map{ _._2 })
}
解决方案是将操作与正确的布尔值配对,在一个列表中,过滤掉具有不真实布尔值的对,将过滤后的对映射到一个操作列表(基本上删除每个幸存对的布尔部分),然后递归地累积你的转换在您的输入数据上。
以下是使用一些简单运算符的结果: import scala.annotations.tailrec
def op1(s: Seq[Int]) = s map {_ + 1}
def op2(s: Seq[Int]) = s map {_ * 2}
def op3(s: Seq[Int]) = s map {_ - 5}
def process(data: Seq[Int], b1:Boolean, b2:Boolean, b3:Boolean): Seq[Int] = {
@tailrec
def loop (acc: Seq[Int], ops: List[Seq[Int] => Seq[Int]]): Seq[Int] = {
ops match {
case List () => acc
case head :: tail => loop (head(acc), tail)
}
}
loop (data, List(( b1,op1 _), (b2,op2 _),(b3,op3 _)).filter{ _._1 }.map{ _._2 })
}
process(Seq(1,2,3), true, false, true) // Seq[Int] = List(-3, -2, -1)
process(Seq(1,2,3), true, false, false) // Seq[Int] = List(2, 3, 4)
process(Seq(1,2,3), false, true, false) // Seq[Int] = List(2, 4, 6)