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 unfoldr
. Basically A
is the type of the resulting iterator (i.e. list) and B
is the state.
There are two things I'd like to give stronger types to:
- I'd like to be able to say
Tuple<A,B>
instead of justTuple
- I'd like to be able to define the arguments of the closure, not just the result type.
Example code which generates an iterator which enumerates from 1 to 100 is below and linked on ideone here.
class Unfoldr<A,B> implements java.util.Iterator<A>
{
public Unfoldr(Closure<Tuple> 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<Tuple> f;
private Tuple state;
}
def unfoldr = { f, init -> new Unfoldr(f, init) };
def u = unfoldr({ x -> if (x < 100) { new Tuple(x + 1, x + 1) } else null; }, 0);
for(e in u)
{
print e;
print "\n";
}
CompileStatic
, is that what you want? Or you want to declare theprivate Closure<Tuple> f
arguments type? Likeprivate Closure<A1, A2, Tuple> f
? – Ferityprivate Closure<Tuple<A, B>, C> f
was what I was really looking for. – Cipher