我正在尝试在
Java中定义类似于Haskell的仿函数的类.因此,仿函数定义为:
/**
* Programming languages allow only (just simply enough) endofunctor, that are functors from and to the same category.
* In this case, the category is the one of the datatypes (in here Type, in order to make it more clear)
*/
public interface EndoFunctor extends Type {
/**
* The basic implementation for any element fx
* @param map Transformation function for the type parameter
* @param fx Element of the current class
* @param Target type
* @return transformed element through map
*/
EndoFunctor fmap(Function map, EndoFunctor fx);
}
如果我想实现一个仿函数,我必须写一些类似的东西
public class Id implements EndoFunctor {
protected X witness;
Id(X witness) { this.witness = witness; }
@Override
public Id fmap(Function map, Id fx) {
return new Id<>(map.apply(fx.witness));
}
}
该代码的问题在于Id< X>与EndoFunctor< X>类型不匹配.我如何在EndoFunctor接口中确定fmap,以便如果任何类型K< T>实现EndoFunctor< T>并且给出映射函数T-> U,然后K< U>.作为值返回,没有任何类型转换(也就是说,因为我知道我的对象是Id< T>,然后fmap的结果“必须是”Id< U>“,因此我向下转换类型的结果EndoFunctor< U>到这种类型)?