title: Groovy Functional Programming: Round-Robin Filter
body: <p>On my quest to learn (more) functional programming, I have a semi-contrived example that I'm able to write an adequate solution for imperatively, but a functional solution is confounding me.</p>
  
  <p>Given a method which returns a <code>List</code> in round-robin fashion, I want to repeatedly call this method until the first element in the <code>List</code> passes some criteria. But I must avoid an infinite loop in case none of the elements meet the criteria.</p>
  
  <p>Here is how I've solved the problem imperatively.</p>
  
  <pre><code>class RoundRobin {
      private final Random random = new Random()
      private final int size = random.nextInt(5) + 5
      private final List&lt;Integer&gt; list = (0..size).collect { random.nextInt(10) }
  
      List&lt;Integer&gt; list() {
          Collections.rotate(list, -1)
          return list.asImmutable()
      }
  }
  
  class RoundRobinFilter {
      static final RoundRobin RR = new RoundRobin()
      static void main(String... args) {
          println filterProcedural()
      }
  
      static List&lt;Integer&gt; filterProcedural() {
          int count = 0
          while (true) {
              List&lt;Integer&gt; candidate = RR.list()
              println candidate
  
              if (candidate.first() &gt; 8) {
                  return candidate
              }
              if (++count &gt;= candidate.size()) {
                  return []
              }
          }
      }
  }
  </code></pre>
  
  <p>Stylistically, I don't like the mutable index variable; I don't like the unconditional loop; and I don't like the branching return statements. In short, I'd like to write this in a functional programming style.</p>
  
  <p>Here is my attempt.</p>
  
  <pre><code>static List&lt;Integer&gt; filterFunctional() {
      List&lt;Integer&gt; candidate = RR.list()
      candidate.findResult([]) {
          println candidate
          return candidate.first() &gt; 8 ? candidate : {candidate = RR.list(); null}.call()
      }
  }
  </code></pre>
  
  <p>This is shorter, but still includes a mutable variable, repeats the <code>list()</code> call twice, and has a ridiculous closure to produce a side effect and return <code>null</code>.</p>
  
  <p>Please show me a functional way to solve this problem.</p>