title: Conditionally apply a function in Scala - How to write this function?
body: <p>I need to conditionally apply a function f1 to the elements in a collection depending on the result of a function f2 that takes each element as an argument and returns a boolean. If f2(e) is true, f1(e) will be applied otherwise 'e' will be returned "as is".
  My intent is to write a general-purpose function able to work on any kind of collection.</p>
  
  <pre><code>c: C[E] // My collection 
  f1 = ( E =&gt; E )  // transformation function
  f2 = ( E =&gt; Boolean )  // conditional function
  </code></pre>
  
  <p>I cannot come to a solution. Here's my idea, but I'm afraid I'm in high-waters</p>
  
  <pre><code>/* Notice this code doesn't compile ~ partially pseudo-code */
  conditionallyApply[E,C[_](c: C[E], f2: E =&gt; Boolean, f1: E =&gt; E): C[E] = {
    @scala.annotation.tailrec
    def loop(a: C[E], c: C[E]): C[E] = {
      c match {
        case Nil =&gt; a // Here head / tail just express the idea, but I  want to use a generic collection
        case head :: tail =&gt; go(a ++ (if f2(head) f1(head) else head ), tail)
      }
    }
    loop(??, c)  // how to get an empty collection of the same type as the one from the input?
  }
  </code></pre>
  
  <p>Could any of you enlighten me?</p>