我正在尝试实现IFunctor
接口[Haskell的Fuctor类]和Maybe
接口来创建两个类:Just
和Nothing
。< / p>
到目前为止,我有:
public interface IFunctor<A> {
IFunctor<B> fmap<B> (Func<A,B> f);
}
public interface Maybe<A> : IFunctor<A> {
Maybe<B> fmap<B> (Func<A,B> f);
}
public class Nothing<A> : Maybe<A> {
public Maybe<B> fmap<B>( Func<A,B> f ){
return new Nothing<B>();
}
}
但是我得到了
`Pr.Nothing<A>' does not implement interface member `IFunctor<A>.fmap<B>
(System.Func<A,B>)' and the best implementing candidate `Pr.Nothing<A>.fmap<B>
(System.Func<A,B>)' return type `Pr.Maybe<B>' does not match interface member return
type `IFunctor<B>'
不是Maybe<B>
IFunctor<B>
成员吗?
解决方案
我结束了写作
public interface IFunctor<A> {
IFunctor<B> fmap<B> (Func<A,B> f);
}
public interface Maybe<A> : IFunctor<A> {
//Some stuff but not fmap
}
public class Nothing<A> : Maybe<A> {
public IFunctor<B> fmap<B>( Func<A,B> f ){
return new Nothing<B>();
}
}
答案 0 :(得分:6)
Maybe<A>.fmap()
没有override
IFunctor<A>.fmap()
。任何实现Maybe<A>
的类型都需要实现 Maybe<A>
和IFunctor<A>
。
public interface IFunctor<A>
{
IFunctor<B> fmap<B>(Func<A, B> f);
}
public interface Maybe<A> : IFunctor<A>
{
Maybe<B> fmap<B>(Func<A, B> f);
}
public class Nothing<A> : Maybe<A>
{
public Maybe<B> fmap<B>(Func<A, B> f)
{
return new Nothing<B>();
}
//This is the explicit implementation of IFunctor<A>.fmap<B>
//which in turn invokes method above.
IFunctor<B> IFunctor<A>.fmap<B>(Func<A, B> f)
{
return this.fmap(f);
}
}