我正在尝试在Java中定义类,使其类似于Haskell的functors。这里,functor被定义为:
/**
* 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<X extends Type> 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 <Y> Target type
* @return transformed element through map
*/
<Y extends Type> EndoFunctor<Y> fmap(Function<X,Y> map, EndoFunctor<X> fx);
}
public class Id<X extends Type> implements EndoFunctor<X> {
protected X witness;
Id(X witness) { this.witness = witness; }
@Override
public <Y extends Type> Id<Y> fmap(Function<X, Y> map, Id<X> 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>
的结果向下转换为这种类型)。
EndoFunctor<Y> fmap(Function<X,Y> map)
呢?这样,每个实例都将使用其实例变量。例如:return new Id<>(map.apply(this.witness))
。 - afsantosfmap2(x)
)可以定义为fmap(x,this)
,所以这并没有真正解决类型问题。 - jackbId
实现中,我觉得你限制了参数范围只能是Id
的实例。我试图理解是否有可能让Id
接受任何其他 Functor 类型的参数。 - afsantostrait Functor[F[_]] { def fmap[A,B](g: A => B)(f: F[A]): F[B] }
- user2297560