title: Why does filter(_:)’s predicate get called so many times when evaluating it lazily?
body: <p>I saw <a href="https://stackoverflow.com/a/41872060/2976878">an answer</a> to <a href="https://stackoverflow.com/q/41871861/2976878">this question</a>, which, in it’s first revision, had code similar to this:</p>
  
  <pre><code>let numbers = Array(0 ..&lt; 50)
  
  let result = numbers.lazy
      .filter {
          // gets called 2-3x per element in the range (0...15)!
          print("Calling filter for: \($0)")
          return $0 % 3 == 0
      }
      .prefix(5)
  
  print(Array(result)) // [0, 3, 6, 9, 12]
  </code></pre>
  
  <p>Which, through the use of a lazy filter collection, is able to filter the first 5 elements of <code>numbers</code> that satisfy a given predicate (in this case, being divisible by 3), without having to evaluate <em>every</em> element in the <code>numbers</code> array.</p>
  
  <p>However, the answer then remarked that <code>filter(_:)</code>’s predicate could be called multiple times per element (3 times for elements in the range 1...15, and twice for 0 as it turns out).</p>
  
  <p>What’s the reason for this inefficiency in the lazy evaluation of this filter? Is there any way to avoid the evaluation of the same element multiple times?</p>