0

I am trying to implement an IFunctor interface [Haskell's Fuctor class] and a Maybe interface to create two classes: Just and Nothing.

So far I have:

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>();
    }
}

However I get

`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>'

Isn't Maybe<B> a member of IFunctor<B>?

Solution

I ended writing

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>();
    }
}
1
  • all your interface have function fmap<B> (Func<A,B> f) so you need implement this function in derived class for each interface, otherwise you can get error when try (IFunctor<A>)Nothing<A> Commented Jun 20, 2014 at 5:32

1 Answer 1

7

Maybe<A>.fmap() does not override IFunctor<A>.fmap(). Any type that implements Maybe<A> will need to need to implement both Maybe<A> and 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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

If I where to override, because that the intention, I would override on Maybe?
You cannot override method definitions in a interface. An interface is a contract, and therefore a way to assume functionality about the implementer. If one were to override methods it could result in undefined behaviour.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.