gpt4 book ai didi

java - 如何递归引用泛型参数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:23:07 35 4
gpt4 key购买 nike

我已经解决了一个 Y 组合器问题。刚才发现不能递归引用泛型参数。

Y = λf.(λx.f (x x)) (λx.f (x x))

例如:

IntUnaryOperator fact = Y(rec -> n -> n == 0 ? 1 : n * rec.applyAsInt(n - 1));

IntUnaryOperator Y(Function<IntUnaryOperator, IntUnaryOperator> f) {
return g(g -> f.apply(x -> g.apply(g).applyAsInt(x)));
}

IntUnaryOperator g(G g) {
return g.apply(g);
}

// v--- I want to remove the middle-interface `G`
interface G extends Function<G, IntUnaryOperator> {/**/}

:如何在方法g上使用泛型参数来避免引入额外的接口(interface)G,泛型参数应该避免UNCHECKED 警告?

提前致谢。

最佳答案

您可以使用递归类型定义来声明泛型方法

<G extends Function<G, IntUnaryOperator>> IntUnaryOperator g(G g) {
return g.apply(g);
}

不起作用的是,使用 lambda 表达式调用此方法,将 lambda 表达式分配给 GThe specification

15.27.3. Type of a Lambda Expression

A lambda expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) …

G不是函数式接口(interface),而是类型参数,这里无法推断出G的实际接口(interface)类型。

当您为 lambda 表达式使用实际接口(interface) G 时,这仍然有效:

IntUnaryOperator Y(Function<IntUnaryOperator, IntUnaryOperator> f) {
return g((G)g -> f.apply(x -> g.apply(g).applyAsInt(x)));
}

// renamed the type parameter from G to F to avoid confusion
<F extends Function<F, IntUnaryOperator>> IntUnaryOperator g(F f) {
return f.apply(f);
}

// can't get rid of this interface
interface G extends Function<G, IntUnaryOperator> {/**/}

IntUnaryOperator fact = Y(rec -> n -> n == 0 ? 1 : n * rec.applyAsInt(n - 1));

IntUnaryOperator Y(Function<IntUnaryOperator, IntUnaryOperator> f) {
return this.<G>g(g -> f.apply(x -> g.apply(g).applyAsInt(x)));
}

// renamed the type parameter from G to F to avoid confusion
<F extends Function<F, IntUnaryOperator>> IntUnaryOperator g(F f) {
return f.apply(f);
}

// can't get rid of this interface
interface G extends Function<G, IntUnaryOperator> {/**/}

因此方法 g 是通用的,不依赖于接口(interface) G,但接口(interface)仍然需要用作 lambda 表达式的目标类型。

关于java - 如何递归引用泛型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45337241/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com