Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Assuming you want the process signature not to change...</p> <pre><code>// 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] =&gt; Seq[Int]]): Seq[Int] = { ops match { case List () =&gt; acc case head :: tail =&gt; loop (head(acc), tail) } } loop (data, List(( b1,op1 _), (b2,op2 _),(b3,op3 _)).filter{ _._1 }.map{ _._2 }) } </code></pre> <p>The solution is to pair the op with the correct Boolean, in a List, filter out the pairs with untrue Booleans, map the filtered pairs to a list of ops (basically dropping the boolean part of each surviving pair), Then accumulate your transformations recursively over your input data.</p> <p>Here's what it results with some simple operators: import scala.annotations.tailrec</p> <pre><code>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] =&gt; Seq[Int]]): Seq[Int] = { ops match { case List () =&gt; acc case head :: tail =&gt; 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) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload