mic*_*hid 12 java functor higher-kinded-types catamorphism fixed-point-iteration
我最近发现了如何 以某种迂回的方式在 Java 中模拟高阶类型,如下所示
interface H<F, T> { }
Run Code Online (Sandbox Code Playgroud)
这里H编码一个高阶类型,它采用类型参数,F该类型参数本身采用参数T。
现在这让我想知道,我们可以用它来实现一些更高级的构造吗?例如,Haskell 中的 Fix 等函子的不动点及其相应的变形?
mic*_*hid 10
事实上,这可以通过仔细翻译相应的 Haskell 对应内容来完成。尽管这引入了很多线路噪声,但其实现非常接近原始:
// Encoding of higher kinded type F of T
public interface H<F, T> { }
public interface Functor<F, T> {
<R> H<F, R> map(Function<T, R> f);
}
// newtype Fix f = Fix {unfix::f (Fix f)}
public static record Fix<F extends H<F, T> & Functor<F, T>, T>(F f) {
public Functor<F, Fix<F, T>> unfix() {
return (Functor<F, Fix<F, T>>) f;
}
}
// type Algebra f a = f a -> a
public interface Algebra<F, T> extends Function<H<F, T>, T> {}
// cata :: Functor f => Algebra f a -> Fix f -> a
// cata alg = alg . fmap (cata alg) . unfix
public static <F extends H<F, T> & Functor<F, T>, T> Function<Fix<F, T>, T> cata(Algebra<F, T> alg) {
return fix -> alg.apply(fix.unfix().map(cata(alg)));
}
Run Code Online (Sandbox Code Playgroud)
令人惊讶的是,它可以工作并且可以用于实现例如表达式代数的解释器
// evalExprF :: Algebra ExprF Int
// evalExprF (Const n) = n
// evalExprF (Add m n) = m + n
// evalExprF (Mul m n) = m * n
public static class ExprAlg implements Algebra<Expr, Integer> {
@Override
public Integer apply(H<Expr, Integer> hExpr) {
return Expr.expr(hExpr).match(
conzt -> conzt.n,
add -> add.t1 + add.t2,
mul -> mul.t1 * mul.t2);
}
}
Run Code Online (Sandbox Code Playgroud)
完整的工作示例位于我的GitHub 存储库中。