title: Typed tuples and closures in Groovy
body: <p>I've done a bit of programming and Haskell, and wanted to implement some Haskell list processing functions in Groovy. Below is an implementation of <code>unfoldr</code>. Basically <code>A</code> is the type of the resulting iterator (i.e. list) and <code>B</code> is the state.</p>
  
  <p>There are two things I'd like to give stronger types to:</p>
  
  <ol>
  <li>I'd like to be able to say <code>Tuple&lt;A,B&gt;</code> instead of just <code>Tuple</code></li>
  <li>I'd like to be able to define the arguments of the closure, not just the result type.</li>
  </ol>
  
  <p>Example code which generates an iterator which enumerates from 1 to 100 is below and linked on ideone <a href="http://ideone.com/3nm9ee" rel="nofollow">here</a>.</p>
  
  <pre><code>class Unfoldr&lt;A,B&gt; implements java.util.Iterator&lt;A&gt;
  {
    public Unfoldr(Closure&lt;Tuple&gt; f, B init) 
    {
      this.f = f;
      this.state = f(init);
    }
  
    public synchronized A next() 
    {
      if (hasNext())
      {
        A curr = state.get(0);
        state = f(state.get(1));
        return curr;
      }
      else
      {
        throw java.lang.NoSuchElementException;
      }
    }
  
    public synchronized boolean hasNext() 
    {
      return (state != null);
    }
  
    public void remove() { throw UnsupportedOperationException; }
  
    private Closure&lt;Tuple&gt; f;
  
    private Tuple state;
  }
  
  def unfoldr = { f, init -&gt; new Unfoldr(f, init) };
  
  def u = unfoldr({ x -&gt; if (x &lt; 100) { new Tuple(x + 1, x + 1) } else null; }, 0);
  
  for(e in u)
  {
    print e;
    print "\n";
  }
  </code></pre>