【发布时间】:2013-05-27 00:59:35
【问题描述】:
我做了一些编程和 Haskell,想在 Groovy 中实现一些 Haskell 列表处理功能。下面是unfoldr 的实现。基本上A 是结果迭代器的类型(即列表),B 是状态。
有两件事我想赋予更强的类型:
- 我希望能够说
Tuple<A,B>而不仅仅是Tuple - 我希望能够定义闭包的参数,而不仅仅是结果类型。
生成从 1 到 100 枚举的迭代器的示例代码如下并链接到 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,这是你想要的吗?或者您想声明private Closure<Tuple> f参数类型?喜欢private Closure<A1, A2, Tuple> f? -
你不想解释一下吗?
-
您好。抱歉,我现在已经转换为使用数组,而不是元组。但是,是的,
private Closure<Tuple<A, B>, C> f是我真正想要的。 -
我认为可以通过接口来完成。您还在寻找这个问题的答案吗?
-
威尔,我放弃了一半,但如果有答案,我真的很感兴趣!
标签: haskell types groovy strong-typing